from django.core.management.base import BaseCommand
from django.utils import timezone
from policies.models import Policy, PolicySection


class Command(BaseCommand):
    help = 'Populate the database with professional enterprise policy content'

    def handle(self, *args, **kwargs):
        self.stdout.write('Populating policies...')
        
        # Privacy Policy
        self.create_privacy_policy()
        
        # Terms of Use
        self.create_terms_policy()
        
        # Support Policy
        self.create_support_policy()
        
        self.stdout.write(self.style.SUCCESS('Successfully populated all policies!'))

    def create_privacy_policy(self):
        policy, created = Policy.objects.update_or_create(
            type='privacy',
            defaults={
                'title': 'Privacy Policy',
                'description': 'Our commitment to protecting your privacy and personal data',
                'version': '2.1',
                'effective_date': timezone.now().date(),
            }
        )
        
        # Clear existing sections
        policy.sections.all().delete()
        
        sections = [
            {
                'heading': '1. Introduction and Scope',
                'content': 'GNX Soft Ltd ("GNX," "we," "us," or "our"), a company registered in Bulgaria (Company Registration Number: 207803200, registered office: Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria), acts as a Data Controller under the General Data Protection Regulation (EU) 2016/679 ("GDPR") and Bulgarian Personal Data Protection Act. This Privacy Policy constitutes our commitment to protecting the privacy, security, and fundamental rights of data subjects in accordance with the highest standards of EU data protection law. This policy describes our lawful basis for processing, data handling practices, technical and organizational measures, and your rights as a data subject when you use our enterprise software solutions, websites, and services (collectively, the "Services"). This policy applies to all users of our Services, including enterprise clients in Defense & Aerospace, Healthcare & Medical, Telecommunication, E-commerce, Enterprise, Banking, Public Sector, Food & Beverages, and Oil & Energy industries. We process personal data only where we have a valid legal basis under Article 6 GDPR (consent, contract, legal obligation, vital interests, public task, or legitimate interests). By accessing or using our Services, you acknowledge that you have read, understood, and agree to be bound by this Privacy Policy and our GDPR-compliant data processing practices.',
                'order': 1
            },
            {
                'heading': '2. Information We Collect and Legal Basis',
                'content': 'We collect and process personal data in accordance with GDPR principles of data minimization, purpose limitation, and lawfulness. Categories of personal data and legal basis for processing: (a) Personal Identification Data: Name, email address, phone number, job title, company name, business address, professional credentials - Legal Basis: Contract performance (Article 6(1)(b) GDPR), Legitimate interests (Article 6(1)(f) GDPR); (b) Account Information: Username, encrypted password, user preferences, account settings, multi-factor authentication data - Legal Basis: Contract performance, Security (legitimate interests); (c) Technical Data: IP address, browser type, operating system, device information, unique device identifiers, session data - Legal Basis: Legitimate interests (service security and optimization); (d) Usage and Analytics Data: Log data, access times, pages viewed, features used, interaction patterns, performance metrics - Legal Basis: Legitimate interests (service improvement); (e) Communication Data: Support tickets, email correspondence, chat messages, feedback, recorded calls (with consent) - Legal Basis: Contract performance, Consent (Article 6(1)(a) GDPR); (f) Financial Data: Billing address, invoice details, payment method details (processed by GDPR-compliant payment processors) - Legal Basis: Contract performance, Legal obligation (Article 6(1)(c) GDPR); (g) Professional and Business Data: Job function, industry sector, company size, business requirements, organizational structure - Legal Basis: Contract performance, Legitimate interests; (h) Special Categories: With explicit consent only, we may process special category data as required for Healthcare & Medical, Defense & Aerospace sectors under Article 9 GDPR. We maintain detailed Records of Processing Activities (Article 30 GDPR) available upon request by supervisory authorities.',
                'order': 2
            },
            {
                'heading': '3. How We Collect Information',
                'content': 'We collect information through various methods: (a) Direct Collection: Information you provide when registering, creating an account, submitting support requests, or communicating with us; (b) Automatic Collection: Technical data collected automatically through essential system logs and analytics (Note: We do not use tracking cookies for marketing purposes); (c) Third-Party Sources: Information from business partners, data providers, and public sources; (d) Service Usage: Data generated through your use of our Services, including interactions with features and functionalities; (e) Enterprise Integrations: Information shared through authorized integrations with your enterprise systems.',
                'order': 3
            },
            {
                'heading': '4. Purpose of Processing and Data Minimization',
                'content': 'We process personal data only for specified, explicit, and legitimate purposes in accordance with Article 5 GDPR (purpose limitation principle). We implement data minimization to ensure we collect only data adequate, relevant, and limited to what is necessary. Processing purposes and GDPR compliance: (a) Service Delivery and Contract Performance: To provide, maintain, and improve our Services as contracted, including customization and optimization for Defense & Aerospace, Healthcare & Medical, Telecommunication, E-commerce, Enterprise, Banking, Public Sector, Food & Beverages, and Oil & Energy sectors - Purpose Limitation: Strictly for contracted services; (b) Account Management: To create and manage user accounts, authenticate users, implement role-based access controls, and provide customer support - Data Minimization: Only essential account data collected; (c) Communication: To send service updates, security alerts, technical notices, and respond to inquiries (marketing communications require explicit opt-in consent) - Transparency: Clear opt-out mechanisms provided; (d) Analytics and Service Improvement: To analyze usage patterns, monitor system performance, and generate insights for service improvement using pseudonymized data where possible - Privacy by Design: Analytics designed to minimize personal data exposure; (e) Security and Fraud Prevention: To detect, prevent, and address security issues, fraud, unauthorized access, and ensure data integrity - Legitimate Interests: Overriding legitimate interest in protecting all users; (f) Legal Compliance: To comply with legal obligations under Bulgarian law, EU regulations, GDPR, industry-specific regulations (HIPAA-equivalent, PCI-DSS, defense standards), enforce our terms, and protect legal rights - Legal Obligation: Article 6(1)(c) GDPR; (g) Research and Development: To conduct privacy-preserving research and development using anonymized or pseudonymized data for new products and services - Data Protection by Default: Personal data protection embedded in system design. We do not process personal data for purposes incompatible with the original purposes without obtaining new consent or establishing a new legal basis.',
                'order': 4
            },
            {
                'heading': '5. Data Sharing, Third-Party Processors, and Data Processing Agreements',
                'content': 'We implement strict data sharing controls in compliance with GDPR Chapter V (transfers) and Article 28 (processor requirements). We share personal data only under the following GDPR-compliant circumstances: (a) Data Processors (Article 28 GDPR): We engage carefully vetted third-party processors who perform services on our behalf (EU-based cloud hosting, GDPR-compliant payment processors, privacy-preserving analytics). All processors are bound by comprehensive Data Processing Agreements (DPAs) that include: mandatory GDPR compliance clauses, processing instructions, confidentiality obligations, sub-processor requirements, data subject rights assistance, security measures (Article 32), data breach notification obligations, audit rights, and data deletion requirements. Current processor list available upon request; (b) Sub-Processors: Any sub-processor engagement requires prior written authorization and equivalent GDPR guarantees; (c) Business Partners: With authorized partners for joint service offerings, subject to DPAs and joint controller agreements (Article 26 GDPR) where applicable; (d) Enterprise Administrators: With designated administrators within your organization as per enterprise agreements and role-based access controls; (e) Legal Requirements and Public Authorities: When required by Bulgarian law, EU regulations, court order, or competent supervisory authority request, we will: notify you unless legally prohibited, verify the legitimacy of the request, disclose only minimum necessary data, and document all disclosures; (f) Business Transfers: In connection with mergers, acquisitions, or asset sales, subject to: advance notice to data subjects, continuation of GDPR protections, new controller assuming all obligations, and right to object or request deletion; (g) Explicit Consent: With your explicit, freely given, specific, informed, and unambiguous consent (Article 7 GDPR) for specific purposes, with clear withdrawal mechanism; (h) Vital Interests: To protect vital interests of data subjects or others (Article 6(1)(d) GDPR); (i) Data Protection Authorities: With Bulgarian Commission for Personal Data Protection (CPDP) or other EU supervisory authorities as required. We explicitly DO NOT and WILL NOT: sell personal data, share data for third-party marketing, transfer data to non-GDPR compliant jurisdictions without adequate safeguards, or process data for purposes incompatible with original collection purpose.',
                'order': 5
            },
            {
                'heading': '6. Technical and Organizational Security Measures (Article 32 GDPR)',
                'content': 'We implement state-of-the-art technical and organizational measures to ensure a level of security appropriate to the risk, taking into account the nature, scope, context, and purposes of processing, as well as the risk to rights and freedoms of natural persons. Our comprehensive security framework includes: (a) Encryption and Pseudonymization (Article 32(1)(a)): End-to-end encryption in transit (TLS 1.3/SSL), encryption at rest (AES-256), database encryption, pseudonymization of personal data where appropriate, encrypted backups, and cryptographic key management with hardware security modules (HSM); (b) Confidentiality and Integrity (Article 32(1)(b)): Role-based access controls (RBAC), mandatory multi-factor authentication (MFA), principle of least privilege, zero-trust architecture, need-to-know basis access, segregation of duties, secure authentication protocols, and session management; (c) Availability and Resilience (Article 32(1)(b)): High-availability infrastructure (99.9% uptime SLA), redundant systems and failover mechanisms, distributed denial-of-service (DDoS) protection, load balancing, geographic redundancy, and business continuity planning; (d) Infrastructure Security: EU-based secure data centers (ISO 27001 certified), physical access controls and surveillance, firewalls and network segmentation, intrusion detection and prevention systems (IDS/IPS), vulnerability scanning, and security information and event management (SIEM); (e) Personnel Security: Background checks for all personnel with data access, mandatory GDPR and security training programs, confidentiality and non-disclosure agreements, separation of duties, and immediate access revocation upon termination; (f) Security Monitoring and Incident Response (Article 33): 24/7 continuous security monitoring, threat intelligence and detection, security operations center (SOC), documented incident response procedures, personal data breach notification to CPDP within 72 hours (Article 33), and data subject notification for high-risk breaches (Article 34); (g) Testing and Assessment (Article 32(1)(d)): Regular penetration testing by independent third parties, vulnerability assessments, security audits, code review and static analysis, compliance testing (SOC 2 Type II, ISO 27001, ISO 27018), and Data Protection Impact Assessments (DPIA) for high-risk processing; (h) Data Backup and Recovery: Regular encrypted backups (daily incremental, weekly full), geographically distributed backup storage, disaster recovery procedures (RTO/RPO defined), regular restoration testing, and secure backup deletion; (i) Application Security: Secure software development lifecycle (SSDLC), OWASP Top 10 compliance, input validation and sanitization, SQL injection prevention, cross-site scripting (XSS) protection, CSRF protection, and security headers; (j) Vendor Security: All processors subject to equivalent security requirements, vendor security assessments, contractual security obligations, and regular security audits of critical vendors. We maintain comprehensive documentation of all security measures and regularly review and update our security posture. While we implement industry-leading security measures, we acknowledge that no system can guarantee absolute security, and we maintain cyber insurance and incident response capabilities.',
                'order': 6
            },
            {
                'heading': '7. Data Retention and Deletion (Storage Limitation Principle)',
                'content': 'We implement the GDPR principle of storage limitation (Article 5(1)(e)), retaining personal data only for as long as necessary for the purposes for which it was collected. Our comprehensive data retention framework: (a) Active Service Accounts: Personal data retained for the duration of active account/contract plus statutory retention periods required by Bulgarian and EU law - Retention Period: Duration of contract + 3 years (Bulgarian Obligations and Contracts Act) or industry-specific requirements; (b) Legal and Regulatory Requirements (Article 6(1)(c)): Financial data: 10 years (Bulgarian Corporate Income Tax Act), Accounting records: 10 years, Tax records: 10 years, Employment records: 50 years (Bulgarian Social Security Code), Healthcare data: per applicable medical regulations, Banking/Finance: per PCI-DSS and financial regulations, Defense data: per national security retention requirements; (c) Legitimate Business Purposes: Dispute resolution and legal claims: Duration of limitation period (5 years under Bulgarian law), Audit trails and compliance: 7 years, Security logs: 12 months (minimum), Fraud prevention: 7 years; (d) Data Deletion Procedures: Erasure requests (Right to be Forgotten) processed within 30 days, Secure deletion using data sanitization standards (e.g., DoD 5220.22-M), Multi-stage deletion verification, Processor deletion verification and certification, Backup system purging (completed within 90 days of next backup cycle), Audit trail of deletion activities; (e) Automated Deletion: Automated retention policy enforcement, Scheduled deletion of expired data, Deletion notifications and confirmations, Data retention dashboard for enterprise clients; (f) Right to Object: Data subjects may object to retention, triggering immediate review; (g) Archived and Backup Data: Backup retention: Maximum 90 days, Disaster recovery data: Minimum necessary retention, Archived data marked for deletion when retention period expires, No restoration of deleted personal data without legal requirement; (h) Anonymization: Where possible, personal data anonymized for statistical purposes after retention period, ensuring irreversible anonymization meeting GDPR standards; (i) Industry-Specific Retention: Healthcare & Medical: HIPAA-equivalent retention (minimum 6 years), Banking & Finance: Per financial regulations (10+ years), Defense & Aerospace: Per security clearance requirements, Public Sector: Per Bulgarian State Records Act; (j) Data Retention Register: We maintain a comprehensive data retention schedule documenting: data categories, retention periods, legal basis for retention, deletion procedures, and last review date. Enterprise clients receive detailed retention schedules in Data Processing Agreements. Annual retention policy review ensures continued compliance and data minimization.',
                'order': 7
            },
            {
                'heading': '8. Data Subject Rights - Full GDPR Chapter III Implementation',
                'content': 'As a data subject under GDPR and Bulgarian Personal Data Protection Act, you have comprehensive rights regarding your personal data. We provide mechanisms to exercise these rights free of charge, and we respond within one month (extendable to three months for complex requests with explanation): (a) Right of Access (Article 15 GDPR): Right to obtain confirmation of whether we process your personal data, access to your personal data, information about: processing purposes, data categories, recipients, retention periods, rights (rectification, erasure, restriction, objection, complaint), data source, existence of automated decision-making including profiling, safeguards for international transfers. We provide data in commonly used electronic format via secure portal; (b) Right to Rectification (Article 16 GDPR): Right to obtain rectification of inaccurate personal data without undue delay, right to complete incomplete personal data, including via supplementary statement. We notify all recipients of rectifications unless impossible or disproportionate effort; (c) Right to Erasure - "Right to be Forgotten" (Article 17 GDPR): Right to obtain erasure of personal data without undue delay when: data no longer necessary for purposes, consent withdrawn (and no other legal basis), objection to processing (Article 21), data unlawfully processed, erasure required for legal compliance, data collected for information society services (children). Exceptions: freedom of expression, legal compliance, public interest, establishment/exercise/defense of legal claims. We notify all recipients and processors of erasure; (d) Right to Restriction of Processing (Article 18 GDPR): Right to restrict processing when: accuracy is contested (during verification), processing is unlawful but you oppose erasure, we no longer need data but you need it for legal claims, objection to processing (pending verification). Restricted data marked and processed only with consent or for legal claims; (e) Right to Data Portability (Article 20 GDPR): Right to receive personal data in structured, commonly used, machine-readable format (JSON, XML, CSV), right to transmit data to another controller without hindrance, right to have data transmitted directly to another controller where technically feasible. Applies to data processed by automated means based on consent or contract; (f) Right to Object (Article 21 GDPR): Right to object to processing based on legitimate interests (Article 6(1)(f)) or public interest (Article 6(1)(e)), we cease processing unless we demonstrate compelling legitimate grounds overriding your interests, absolute right to object to direct marketing (we cease immediately), right to object to profiling related to direct marketing; (g) Rights Related to Automated Decision-Making and Profiling (Article 22 GDPR): Right not to be subject to automated decisions producing legal or similarly significant effects, including profiling, exceptions: necessary for contract, authorized by EU/Member State law, based on explicit consent. Where automated decisions used, we provide: information about logic involved, significance and envisaged consequences, right to human intervention, right to express point of view, right to contest decision; (h) Right to Withdraw Consent (Article 7(3) GDPR): Where processing based on consent, right to withdraw at any time (as easy as giving consent), withdrawal does not affect lawfulness of prior processing, clear "withdraw consent" mechanism provided; (i) Right to Lodge Complaint with Supervisory Authority (Article 77 GDPR): Right to lodge complaint with Bulgarian Commission for Personal Data Protection (CPDP): Address: 2 Prof. Tsvetan Lazarov Blvd., Sofia 1592, Bulgaria, Phone: +359 2 915 3518, Email: kzld@cpdp.bg, Website: www.cpdp.bg. Right to lodge with supervisory authority of your habitual residence, place of work, or place of alleged infringement; (j) Right to Effective Judicial Remedy (Article 79 GDPR): Right to judicial remedy against CPDP decisions, right to judicial remedy against GNX Soft Ltd for GDPR violations (Bulgarian courts). How to Exercise Your Rights: Online: Secure data subject rights portal at https://gnxsoft.com/privacy-rights, Email: privacy@gnxsoft.com or dpo@gnxsoft.com, Phone: +359 896 13 80 30, Mail: GNX Soft Ltd, Data Protection Officer, Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria. We verify your identity before processing requests using secure authentication. Enterprise customers have dedicated portals with self-service rights management. We maintain logs of all data subject rights requests and responses for GDPR accountability.',
                'order': 8
            },
            {
                'heading': '9. International Data Transfers (GDPR Chapter V Compliance)',
                'content': 'GNX Soft Ltd operates from Bulgaria (EU member state) and prioritizes EU data localization. Any transfer of personal data to countries outside the European Economic Area (EEA) complies strictly with GDPR Chapter V requirements: (a) Primary Data Location: All personal data primarily stored and processed within EU/EEA data centers (Bulgaria, Germany, Netherlands), EU-based infrastructure providers with GDPR compliance, no routine transfers outside EU/EEA; (b) Legal Mechanisms for Third Country Transfers (Article 45-46 GDPR): European Commission Adequacy Decisions (Article 45): Transfers to countries with adequacy decisions (e.g., UK, Switzerland, Andorra, Argentina, Canada (commercial), Israel, Japan, New Zealand, South Korea, Uruguay), Standard Contractual Clauses - SCCs (Article 46(2)(c)): Updated SCCs adopted by European Commission Decision 2021/914, Module 1 (Controller to Controller), Module 2 (Controller to Processor), Module 3 (Processor to Processor) as applicable, additional safeguards implementing Schrems II requirements, Transfer Impact Assessment (TIA) conducted for all third country transfers, Binding Corporate Rules (BCRs) for intra-group transfers where applicable; (c) Supplementary Measures (Schrems II Compliance): Technical measures: end-to-end encryption, data minimization, pseudonymization, access controls, Contractual measures: data access limitations, disclosure notification requirements, transparency obligations, Legal measures: data protection laws in destination country assessed, government access risk evaluation conducted, Organizational measures: staff training, compliance monitoring, regular reviews; (d) Transfer Impact Assessments (TIA): We conduct comprehensive TIAs evaluating: legislation in third country (surveillance laws, government access), practical application and enforcement, additional safeguards available, whether adequate protection can be ensured, TIA documentation available upon request by supervisory authorities; (e) Specific Transfer Scenarios: Cloud service providers: EU-based infrastructure required or adequacy decision country, payment processors: PCI-DSS compliant with EU operations or SCCs, analytics: EU-based or privacy-preserving with SCCs, support tools: EU-based or adequacy decision country; (f) Data Localization Options: Enterprise clients may require: EU-only data processing, specific country processing, on-premises deployment, private cloud hosting, data residency guarantees in Data Processing Agreements; (g) Notification and Transparency: List of third countries where data may be transferred, legal mechanisms employed, additional safeguards implemented, transfer notifications for enterprise clients, annual transfer inventory; (h) Derogations for Specific Situations (Article 49 GDPR - Used Rarely): Explicit informed consent for specific transfer (not relied upon for repeated transfers), performance of contract between data subject and controller, important reasons of public interest, establishment/exercise/defense of legal claims, protection of vital interests where consent cannot be obtained; (i) Restrictions on Onward Transfers: Sub-processors may not transfer data without equivalent safeguards, written authorization required for onward transfers, same level of protection guaranteed; (j) Government Access Requests: We resist overbroad or unlawful requests from non-EU governments, notify data subjects unless legally prohibited (Article 48 GDPR), document all requests for supervisory authority review, engage legal counsel for foreign government requests; (k) Brexit and UK Transfers: UK currently has adequacy decision (until reassessed), monitoring UK data protection developments, prepared to implement SCCs if adequacy withdrawn; (l) Continuous Monitoring: Regular monitoring of CJEU case law and European Commission guidance, updating transfer mechanisms as required, supervisory authority coordination for cross-border transfers. We commit to no transfers to third countries without adequate GDPR safeguards. Enterprise clients receive detailed transfer documentation in Data Processing Agreements including transfer inventory, safeguards, and TIA summaries.',
                'order': 9
            },
            {
                'heading': '10. Cookies and Tracking Technologies (ePrivacy Directive Compliance)',
                'content': 'Important Notice: GNX Soft Ltd implements privacy-first practices and does NOT use tracking cookies for marketing, advertising, or third-party analytics purposes. We strictly comply with EU ePrivacy Directive (2002/58/EC) and GDPR requirements for cookies and similar technologies: (a) Strictly Necessary Cookies Only (No Consent Required): We use only essential technical cookies strictly necessary for service operation under Article 5(3) ePrivacy Directive exemption: Session management cookies (authentication, session ID), security cookies (CSRF tokens, anti-fraud), load balancing cookies, user interface preferences (language, accessibility), cookie consent status. These cookies: expire after session or maximum 12 months, do not track across sites, contain no personal identifiers, are limited to technical necessity; (b) Explicit No Tracking Policy: No marketing or advertising cookies, no behavioral tracking or profiling cookies, no third-party tracking cookies or pixels, no social media tracking plugins, no cross-site tracking, no tracking for personalized advertising, no analytics cookies (we use server-side analytics); (c) Server-Side Analytics: We use privacy-preserving server-side analytics that: do not store cookies in browser, use anonymized IP addresses (last octet removed), aggregate data only, no individual user tracking, GDPR-compliant processing, no third-party analytics services (Google Analytics, etc.); (d) No Consent Banner Required: Since we use only strictly necessary cookies, we do not require cookie consent banners under ePrivacy Directive, avoiding dark patterns and consent fatigue, transparent cookie notice provided; (e) Cookie Information Provided: Complete list of cookies in Cookie Policy, purpose and duration of each cookie, how to control/delete cookies via browser, no disadvantage for rejecting non-essential cookies (none used); (f) Browser Controls: Users can disable all cookies via browser settings (functionality may be affected), cookie deletion instructions provided, respect for Do Not Track (DNT) signals; (g) Local Storage and Similar Technologies: LocalStorage used only for essential functionality (e.g., UI preferences), no tracking via HTML5 storage, IndexedDB, or similar technologies, regular storage clearing options provided; (h) Third-Party Services: Payment processors (Stripe, etc.) may set strictly necessary cookies under their control, these are disclosed and limited to transaction necessity, Data Processing Agreements ensure GDPR compliance; (i) Mobile Applications: No tracking SDKs or advertising IDs, only essential identifiers for service operation, mobile privacy policies aligned with app store requirements; (j) Email Tracking: No email tracking pixels or open trackers, no click tracking for marketing (transactional email tracking for fraud prevention only), clear unsubscribe mechanism; (k) Cookie Audit: Annual cookie audit to ensure compliance, documentation of all cookies and legal basis, removal of any non-essential cookies, supervisory authority audit preparation; (l) Future Cookie Changes: Advance notice if new cookies introduced, consent obtained if non-essential cookies added, continued commitment to privacy-first approach. Complete Cookie Inventory Available: Cookie Policy accessible at https://gnxsoft.com/cookie-policy, detailed cookie table with: name, purpose, duration, type, legal basis, contact for questions: privacy@gnxsoft.com. We are committed to leading industry standards for privacy-first practices and minimal data collection.',
                'order': 10
            },
            {
                'heading': '11. Industry-Specific Data Handling and Compliance',
                'content': 'GNX Soft Ltd serves clients across multiple regulated industries, and we maintain industry-specific data protection standards with full GDPR integration: (a) Defense & Aerospace: Defense-grade security standards (NATO, national security clearances), special category data handling (Article 9 GDPR), restricted access controls, security clearance verifications, compliance with defense procurement regulations, data sovereignty requirements, air-gapped environments for classified data, and defense-specific retention requirements; (b) Healthcare & Medical: HIPAA-equivalent privacy protections, health data as special category (Article 9(2)(h) GDPR - healthcare exemption), medical confidentiality standards, healthcare data processors agreements, minimum 6-year retention, patient consent management, health information exchange protocols, telemedicine data protection, and medical device data security; (c) Banking & Finance: PCI-DSS Level 1 compliance, financial data security standards, payment card data tokenization, 10-year financial records retention (Bulgarian law), anti-money laundering (AML) data processing, know-your-customer (KYC) compliance, transactional data integrity, fraud detection processing, and financial regulatory reporting; (d) Public Sector: Government data protection requirements, public procurement compliance, Bulgarian State Records Act compliance, GDPR Article 6(1)(e) public interest processing, freedom of information obligations, citizen data protection, inter-agency data sharing protocols, extended retention for administrative proceedings, and public sector accountability; (e) Telecommunication: ePrivacy Directive compliance, telecommunications data retention directive, network security obligations, traffic data protection, location data safeguards, communications confidentiality, lawful intercept compliance (with judicial authorization only), and telecom regulatory standards; (f) E-commerce: Consumer protection regulations, EU Consumer Rights Directive, transaction data security, customer profiling transparency (GDPR Article 22), payment data PCI-DSS, order processing data, customer consent management, direct marketing opt-in requirements, and distance selling regulations; (g) Food & Beverages: Food safety data management, supply chain traceability data, allergen information handling, regulatory compliance data (EFSA), quality control records, product recall data management, supplier data protection, and food safety incident reporting; (h) Oil & Energy: Critical infrastructure data protection (NIS Directive), trade secrets protection, operational technology (OT) security, SCADA system data protection, energy sector regulatory compliance, environmental data management, resource exploration data confidentiality, and long-term project data retention. Each industry engagement includes: tailored Data Processing Agreements addressing industry regulations, specific security controls and certifications, industry-appropriate retention schedules, specialized incident response procedures, regulatory liaison protocols, audit and compliance reporting, sector-specific training for staff handling data, and continuous regulatory monitoring. Enterprise clients receive industry-specific compliance documentation and regular compliance attestations.',
                'order': 11
            },
            {
                'heading': '12. Data Breach Notification Procedures (Articles 33-34 GDPR)',
                'content': 'GNX Soft Ltd maintains comprehensive data breach preparedness and response procedures in strict compliance with GDPR Articles 33 (notification to supervisory authority) and 34 (communication to data subjects): (a) Breach Detection and Monitoring: 24/7 security monitoring and incident detection, automated anomaly detection systems, security information and event management (SIEM), intrusion detection and prevention systems (IDS/IPS), log analysis and correlation, threat intelligence integration, user behavior analytics, and regular security assessments; (b) Incident Classification: We classify incidents based on GDPR risk criteria: Confirmed Personal Data Breach: unauthorized or unlawful processing, accidental loss, destruction, alteration of personal data, unauthorized disclosure or access; Risk Assessment: likelihood and severity of impact on rights and freedoms, data sensitivity, number of affected data subjects, ease of identification, special category data involvement, and potential consequences; (c) Internal Breach Response (Immediate): Incident response team activation, breach containment and mitigation, forensic investigation, affected systems isolation, root cause analysis, evidence preservation, documentation of breach timeline and impact, and preliminary risk assessment; (d) Notification to Supervisory Authority (Article 33 - Within 72 Hours): We notify the Bulgarian Commission for Personal Data Protection (CPDP) within 72 hours of breach awareness, including: nature of personal data breach (categories and approximate number of data subjects, categories and approximate number of records), contact details of DPO or contact point, description of likely consequences, measures taken or proposed to address breach and mitigate adverse effects. If notification exceeds 72 hours, we provide reasons for delay. Breach register maintained with all breach details; (e) Communication to Data Subjects (Article 34 - Without Undue Delay): When breach likely to result in high risk to rights and freedoms, we communicate to affected data subjects in clear and plain language, including: nature of personal data breach, contact details of DPO, likely consequences of breach, measures taken or proposed to address and mitigate adverse effects. Exemptions from data subject notification: appropriate technical and organizational protection measures applied (e.g., encryption), subsequent measures ensure high risk unlikely, or notification requires disproportionate effort (public communication alternative); (f) Exceptions to Notification: Data rendered unintelligible (strong encryption with keys secured), risk mitigated by immediate remedial action, notification would cause disproportionate harm, subject to supervisory authority approval; (g) Cross-Border Breach Coordination: Lead supervisory authority identified (Bulgaria), cooperation with concerned supervisory authorities, one-stop-shop mechanism application, consistent breach response across EU, and coordination for cross-border notifications; (h) Breach Documentation and Register: We maintain comprehensive records of all breaches (regardless of notification requirement), including: facts of breach, effects and consequences, remedial action taken, breach register available for CPDP inspection; (i) Post-Breach Activities: Lessons learned analysis, security measures enhancement, updated risk assessments, staff training updates, policy and procedure improvements, and supervisory authority cooperation; (j) Enterprise Client Notification: Contractual notification obligations to enterprise clients, processor breach notification to controllers without undue delay (within 24 hours), joint breach response coordination, and client support for controller obligations; (k) Communication Channels: Dedicated breach hotline: breach@gnxsoft.com (24/7 monitored), emergency phone: +359 896 13 80 30, web portal: https://gnxsoft.com/security-incident, and CPDP notification portal; (l) Transparency: Public breach notifications for high-impact incidents (subject to law enforcement and security considerations), transparency reports (annual breach statistics), and continuous improvement commitment. We maintain cyber insurance and engage specialized incident response firms for major breaches. Regular breach simulation exercises ensure preparedness.',
                'order': 12
            },
            {
                'heading': '13. Privacy by Design and by Default (Article 25 GDPR)',
                'content': 'GNX Soft Ltd implements Privacy by Design and Privacy by Default principles as required by Article 25 GDPR, embedding data protection into all processing activities and systems from the earliest design stages: (a) Privacy by Design Principles: Data Protection from Outset: Privacy considerations integrated from initial system design and throughout development lifecycle; Proactive not Reactive: Anticipating and preventing privacy issues before they occur; Privacy as Default: Highest privacy settings applied automatically without user action; Privacy Embedded into Design: Privacy fundamental component of system architecture, not add-on; Full Functionality (Positive-Sum): Privacy compatible with business objectives (not zero-sum trade-off); End-to-End Security: Data protected throughout entire lifecycle (collection to deletion); Visibility and Transparency: Operations visible and subject to independent verification; Respect for User Privacy: User-centric design prioritizing data subject interests; (b) Technical Measures: Data Minimization by Design: Systems configured to collect only necessary data, default forms request minimum information, optional vs. required fields clearly marked, automated data collection limited to essential, unused data fields removed from systems; Pseudonymization and Anonymization: Automated pseudonymization where full identification not required, anonymization for analytics and reporting, separation of identifying data from operational data, irreversible anonymization techniques for statistical use; Encryption by Default: All personal data encrypted at rest (AES-256), all data in transit encrypted (TLS 1.3), end-to-end encryption for sensitive communications, cryptographic key management with HSM, quantum-resistant encryption preparedness; Access Controls: Role-based access control (RBAC) with least privilege, multi-factor authentication default, session timeout mechanisms, audit logging of all data access, segregation of duties enforcement, need-to-know basis access restrictions; (c) Organizational Measures: Privacy-First Culture: GDPR training for all staff (mandatory), privacy awareness programs, privacy champions in each department, privacy considerations in project management, data protection impact assessments as standard, privacy incident reporting channels; Default Privacy Settings: Highest privacy protection as default (users opt-in to share more, not opt-out), marketing communications opt-in only (no pre-checked boxes), data sharing off by default, retention periods automatically enforced, privacy-preserving defaults for all new features; Privacy in Procurement: GDPR requirements in vendor selection, processor due diligence standard procedure, DPAs required before data sharing, privacy requirements in RFPs, vendor privacy audits; (d) System Design Practices: Privacy Impact Screening: All new projects screened for privacy impact, DPIA conducted for high-risk processing, privacy review gates in development, privacy sign-off required for production deployment; Secure Development: Secure software development lifecycle (SSDLC), privacy requirements in design specifications, privacy-focused code reviews, security testing including privacy scenarios, penetration testing covering privacy aspects; API and Integration Privacy: APIs designed with privacy controls, third-party integrations minimize data exposure, data filtering at integration points, automated PII detection and protection, API access logs and monitoring; (e) Data Lifecycle Privacy: Collection: Purpose disclosed before collection, consent obtained where required, data minimization enforced, retention period specified upfront; Processing: Purpose limitation enforced, automated controls prevent incompatible processing, processing logs maintained, regular processing audits; Storage: Encrypted storage default, access logging, retention automation, secure deletion scheduling; Deletion: Automated deletion upon retention expiry, secure sanitization standards, deletion verification and certification, backup purging processes; (f) Privacy-Enhancing Technologies (PETs): Differential privacy for statistical analysis, homomorphic encryption exploration for computation on encrypted data, secure multi-party computation for collaborative processing, zero-knowledge proofs for verification, federated learning for distributed AI, privacy-preserving analytics tools; (g) Monitoring and Improvement: Privacy metrics dashboard, privacy KPIs tracked, regular privacy audits, user privacy feedback mechanisms, continuous improvement processes, lessons learned from incidents, industry best practices monitoring; (h) Documentation: Design documentation includes privacy analysis, privacy decisions recorded and justified, trade-off analysis for privacy vs. functionality, technical specifications include privacy controls, architecture diagrams show data flows and protections. Our Privacy by Design approach ensures GDPR compliance is fundamental to our operations, not an afterthought, providing maximum protection for data subjects while enabling effective business operations.',
                'order': 13
            },
            {
                'heading': '14. Data Protection Impact Assessments (Article 35 GDPR)',
                'content': 'GNX Soft Ltd conducts Data Protection Impact Assessments (DPIAs) in accordance with Article 35 GDPR for processing operations likely to result in high risk to data subjects\' rights and freedoms: (a) When DPIA Required: Systematic and extensive evaluation/scoring/profiling with legal or significant effects (Article 35(3)(a)); Processing special category data (Article 9) or criminal convictions data (Article 10) at large scale (Article 35(3)(b)); Systematic monitoring of publicly accessible areas at large scale (Article 35(3)(c)); New technologies with high risk to rights and freedoms; Processing involving innovative technology use; Processing preventing data subjects from exercising rights/using services; Processing on large scale; Matching or combining datasets; Processing vulnerable individuals\' data (children, employees, patients); Automated decision-making (Article 22) with legal/significant effects; Processing involving transfer outside EU/EEA; Processing that could lead to physical harm; Processing likely to result in discrimination; (b) DPIA Methodology: Systematic Description: Description of processing operations and purposes, assessment of necessity and proportionality, legitimate interests assessment, data flows mapping, system architecture review, involved parties identification; Risk Assessment: Identification of risks to data subjects (not organization risks), likelihood assessment (rare, possible, likely), severity assessment (limited, significant, severe), risk scenarios analysis, consideration of special category data, vulnerable populations assessment; Measures to Address Risks: Technical safeguards (encryption, pseudonymization, access controls), organizational measures (policies, training, oversight), measures to ensure compliance, demonstration of GDPR principles, accountability measures, residual risk evaluation; Stakeholder Consultation: Data Protection Officer consultation (mandatory), data subjects consultation where appropriate, relevant expert consultation, supervisory authority consultation when necessary; Documentation: Written DPIA report maintained, review and update as needed, DPIA register maintained, available for supervisory authority review; (c) Prior Consultation (Article 36 GDPR): If DPIA indicates high risk cannot be mitigated, we consult Bulgarian CPDP before processing, providing: DPIA results and risk assessment, planned measures to address risks, processing responsibilities (controller/processor/joint controllers), lawful basis for processing, legitimate interests assessment, data subject rights safeguards. CPDP may provide written advice within 8 weeks (or 14 weeks for complex cases); (d) DPIA Review and Updates: Regular DPIA reviews (at least annually), updates when processing changes materially, updates following privacy incidents, updates when new risks identified, updates based on supervisory authority guidance, continuous improvement of DPIA process; (e) Industry-Specific DPIAs: Defense & Aerospace: Classified data processing, security clearance data, dual-use technology; Healthcare & Medical: Health data processing, genetic data, biometric data, patient profiling; Banking & Finance: Credit scoring, fraud detection algorithms, large-scale financial profiling; Public Sector: Citizen data processing, law enforcement cooperation, welfare systems; Telecommunication: Traffic data analysis, location tracking, communications metadata; E-commerce: Customer profiling, behavioral advertising, recommendation algorithms; Each industry receives tailored DPIA frameworks; (f) DPIA for AI and Automated Decision-Making: Algorithm logic documentation, bias and discrimination assessment, explanation and transparency measures, human oversight mechanisms, appeal and contestation procedures, fairness assessment, accuracy and reliability evaluation; (g) DPIA Governance: DPO oversight of all DPIAs, DPIA review committee, executive sign-off for high-risk processing, DPIA training for project teams, DPIA templates and tools provided, quality assurance of DPIA process; (h) Consultation with Bulgarian CPDP: DPIA list available for CPDP review, prior consultation when high residual risk, cooperation with CPDP recommendations, transparency with supervisory authority, documented CPDP consultations; (i) Enterprise Client DPIAs: Joint controller DPIAs where applicable, processor input to controller DPIAs, DPIA support services for enterprise clients, sharing of relevant DPIA findings, coordinated risk mitigation; (j) Accountability and Documentation: DPIA register maintained with: processing operation description, DPIA date and reviewers, risk assessment results, mitigation measures, review dates, supervisory authority consultations. All DPIAs available for audit and supervisory authority inspection. We demonstrate GDPR compliance through comprehensive DPIA documentation and continuous risk management.',
                'order': 14
            },
            {
                'heading': '15. Records of Processing Activities (Article 30 GDPR)',
                'content': 'As a Data Controller under GDPR Article 30, GNX Soft Ltd maintains comprehensive written records of all processing activities under our responsibility, available to the Bulgarian Commission for Personal Data Protection (CPDP) upon request: (a) Controller Records (Article 30(1)): Our records contain: Organization Details: Name and contact details of controller (GNX Soft Ltd, Company Registration: 207803200, Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria), contact details of Data Protection Officer (dpo@gnxsoft.com, +359 896 13 80 30), where applicable, representative in the EU; Processing Purposes: Purposes of processing for each category, detailed purpose descriptions, legitimate interests where applicable, lawful basis for processing (Article 6 GDPR); Data Categories: Categories of data subjects (customers, employees, enterprise users, website visitors, support contacts), categories of personal data (identification, contact, financial, technical, usage, communications, professional), special category data processed (health, biometric, etc. - Article 9), criminal convictions data (if any - Article 10); Recipients: Categories of recipients (processors, sub-processors, business partners, authorities), specific recipients where relevant, recipients in third countries, safeguards for transfers; International Transfers: Third countries or international organizations receiving data, documentation of appropriate safeguards (SCCs, adequacy decisions, BCRs), Transfer Impact Assessments (TIAs), derogations applied (Article 49); Retention Periods: Time limits for erasure of data categories, retention schedules by data type, legal retention requirements, deletion procedures; Security Measures: General description of technical and organizational security measures (Article 32), encryption methods, access controls, monitoring systems, incident response procedures; (b) Processor Records (Article 30(2)) - Where We Act as Processor: Name and contact details of processor and controllers, Data Protection Officer contact details, categories of processing on behalf of each controller, international transfers and safeguards, security measures description; (c) Record Format and Maintenance: Written records (electronic format), structured and searchable database, regular updates reflecting processing changes, version control and audit trail, annual comprehensive review, accessible to authorized personnel, immediately available for CPDP requests; (d) Processing Activity Inventory: We maintain detailed records for each processing activity: Activity identifier and name, business function/department, processing description, data subjects categories, personal data categories, lawful basis (specific Article 6/9 GDPR provision), legitimate interests assessment (where applicable), consent records (where applicable), purpose specification, data sources, recipients and disclosure, retention period and deletion, security measures, DPIA reference (if conducted), DPA reference (for processors), transfer mechanisms (for international), last review date; (e) Industry-Specific Processing Records: Defense & Aerospace: Classified data processing, security clearance processing, defense contractor data; Healthcare & Medical: Patient data, health records, medical device data, clinical trial data; Banking & Finance: Customer financial data, transaction processing, AML/KYC data; Public Sector: Citizen data, administrative processing, public services data; Telecommunication: Traffic data, location data, communications metadata; E-commerce: Customer data, transaction data, marketing data; Food & Beverages: Supply chain data, food safety data, customer data; Oil & Energy: Operational data, employee data, contractor data. Sector-specific retention and security documented; (f) Special Category Data Processing (Article 9): Explicit documentation of lawful basis for special category processing: explicit consent (Article 9(2)(a)), employment/social security law (Article 9(2)(b)), vital interests (Article 9(2)(c)), legitimate activities of foundation/association (Article 9(2)(d)), data manifestly made public (Article 9(2)(e)), legal claims (Article 9(2)(f)), substantial public interest (Article 9(2)(g)), healthcare (Article 9(2)(h)), public health (Article 9(2)(i)), archiving/research/statistics (Article 9(2)(j)). Additional safeguards documented for each special category processing activity; (g) Joint Controller Records (Article 26): Where joint controllership exists: arrangement with other controller(s), essence of arrangement made available to data subjects, respective responsibilities documented, single point of contact designated, coordinated records maintenance; (h) Record Review and Updates: Continuous updates as processing activities change, quarterly review of records accuracy, annual comprehensive audit, updates following DPIAs, updates following supervisory authority guidance, version history maintained; (i) Accountability and Availability: Records demonstrating GDPR compliance, immediately available for CPDP inspection, accessible to DPO at all times, integrated with compliance management system, referenced in internal audits, supporting evidence maintained (DPIAs, DPAs, consent forms, policies); (j) Enterprise Client Transparency: Relevant processing records shared with enterprise clients, transparency in processor activities, annual processing activity reports, changes communicated promptly, audit rights facilitated. Our comprehensive Records of Processing Activities demonstrate our accountability under GDPR Article 5(2) and enable effective supervisory authority oversight. We maintain these records as living documents, continuously updated to reflect our actual processing operations and ensure full transparency and compliance.',
                'order': 15
            },
            {
                'heading': '16. Children\'s Privacy (GDPR Article 8)',
                'content': 'Our Services are designed for business and enterprise use and are not directed to individuals under 16 years of age (the minimum age for information society services consent under GDPR Article 8(1)). We do not knowingly collect personal data from children under 16 without parental consent. Age Verification: We implement age verification mechanisms where appropriate; Parental Consent: For any processing of children\'s data (e.g., educational services), we obtain verifiable parental or guardian consent; Immediate Deletion: If we discover inadvertent collection of data from children under 16 without proper consent, we delete it immediately; Reporting: Parents or guardians who believe we have collected information from a child under 16 should contact us at privacy@gnxsoft.com, dpo@gnxsoft.com, or +359 896 13 80 30. We will investigate and take appropriate action within 72 hours; Special Protections: Where children\'s data is processed with consent (e.g., educational programs), we apply enhanced protections: age-appropriate privacy notices, strict access controls, no profiling or automated decision-making, no marketing to children, parental access rights to children\'s data, enhanced security measures, shorter retention periods, child-safe design principles. Industry-Specific Children Protections: Healthcare & Medical: pediatric patient data subject to enhanced confidentiality; Public Sector: student data in educational services strictly protected; E-commerce: no marketing or sales to children. We are committed to protecting children\'s privacy rights and ensuring GDPR Article 8 compliance.',
                'order': 16
            },
            {
                'heading': '17. Changes to This Privacy Policy',
                'content': 'We may update this Privacy Policy periodically to reflect changes in our practices, technologies, legal requirements, or business operations, while maintaining full GDPR compliance: (a) Notification Methods: Material changes communicated via: email notification to registered users (30 days advance notice), prominent banner notice on website, in-app notifications, push notifications where applicable, updates to "Effective Date" and version number, summary of changes provided; (b) Effective Date: Changes become effective 30 days after notification (unless otherwise specified or required by law), immediate effect for changes required by law or supervisory authority, deferred effect for changes adverse to data subjects; (c) Continued Use: Continued use of Services after effective date constitutes acceptance of revised Privacy Policy, except where explicit consent required for material changes; (d) Right to Object: If you object to changes, you may: discontinue use of Services, exercise right to erasure (deletion) of your data, object to new processing purposes, withdraw consent where applicable. We will honor deletion requests within 30 days; (e) Material Changes: Material changes include: new data processing purposes, new categories of data collected, new third-party recipients, changes to international data transfers, changes to data retention periods, changes to data subject rights, changes to legal basis for processing. Material changes require explicit notice and may require new consent where original consent was legal basis; (f) Non-Material Changes: Minor updates (contact information, clarifications, formatting) effective immediately with update notice; (g) Enterprise Customer Notification: Enterprise customers receive: direct account manager notification, detailed change analysis, impact assessment for their operations, reasonable time to review and provide feedback, amendment to Data Processing Agreements where necessary; (h) Version History: We maintain version history of all Privacy Policy iterations, previous versions available upon request, changelog documenting all changes, effective dates of each version; (i) Documentation for Supervisory Authority: All policy changes documented in Records of Processing Activities, change rationale documented, GDPR compliance verified for all changes, supervisory authority notified of significant changes where required; (j) Regular Reviews: Comprehensive privacy policy review conducted annually minimum, ad hoc reviews following: changes in data processing, changes in GDPR guidance, supervisory authority recommendations, privacy incidents, technology changes, new service offerings; (k) Transparency: We commit to clear communication of all changes, plain language explanations, avoiding obfuscation of changes, highlighting material changes, providing reasonable time for review. We encourage you to review this Privacy Policy regularly. Current version always available at https://gnxsoft.com/privacy-policy. Contact us with any questions about changes at privacy@gnxsoft.com or dpo@gnxsoft.com.',
                'order': 17
            },
            {
                'heading': '18. Data Protection Officer and Contact Information',
                'content': 'In accordance with Article 37 GDPR, GNX Soft Ltd has appointed a Data Protection Officer (DPO) to oversee GDPR compliance, data protection strategy, and serve as point of contact for data subjects and supervisory authorities. Contact Information: GNX Soft Ltd | Legal Entity: GNX Soft Ltd (Bulgarian Company) | Company Registration: 207803200 | Registered Office: Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria | General Inquiries: privacy@gnxsoft.com | Phone: +359 896 13 80 30 | Data Protection Officer (DPO): GNX Data Protection Team, Email: dpo@gnxsoft.com (monitored 24/7), Phone: +359 896 13 80 30 (DPO line), Address: GNX Soft Ltd, Attn: Data Protection Officer, Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria. The DPO: monitors GDPR compliance (Article 39), advises on Data Protection Impact Assessments, serves as contact point for Bulgarian CPDP and EU supervisory authorities, handles data subject rights requests, conducts staff training on data protection, maintains Records of Processing Activities (Article 30), reviews data processing agreements, investigates data breaches, coordinates incident response. Additional Contacts: Data Subject Rights Requests: privacy@gnxsoft.com, dpo@gnxsoft.com | Security Incidents: security@gnxsoft.com | Data Breach Reporting: breach@gnxsoft.com (24/7 monitored) | Enterprise DPAs: legal@gnxsoft.com | Business Inquiries: sales@gnxsoft.com | Technical Support: support@gnxsoft.com | Support Center Portal: https://gnxsoft.com/support-center | Data Subject Rights Portal: https://gnxsoft.com/privacy-rights | Website: https://gnxsoft.com | Business Hours: Monday-Friday, 9:00 AM - 6:00 PM EET (DPO available outside hours for urgent matters). Response Times: Data subject rights requests: 30 days (maximum, usually faster), complex requests: up to 90 days with explanation, urgent privacy matters: 24-48 hours, data breach inquiries: immediate response, general inquiries: 5 business days. Supervisory Authority: Bulgarian Commission for Personal Data Protection (CPDP) | Address: 2 Prof. Tsvetan Lazarov Blvd., Sofia 1592, Bulgaria | Phone: +359 2 915 3518 | Email: kzld@cpdp.bg | Website: www.cpdp.bg. European Data Protection Board (EDPB): www.edpb.europa.eu. We welcome all privacy inquiries and are committed to transparency, accountability, and GDPR compliance.',
                'order': 18
            },
        ]
        
        for section_data in sections:
            PolicySection.objects.create(policy=policy, **section_data)
        
        self.stdout.write(self.style.SUCCESS(f'Created/Updated Privacy Policy with {len(sections)} sections'))

    def create_terms_policy(self):
        policy, created = Policy.objects.update_or_create(
            type='terms',
            defaults={
                'title': 'Terms of Use',
                'description': 'Terms and conditions governing the use of our services',
                'version': '2.1',
                'effective_date': timezone.now().date(),
            }
        )
        
        # Clear existing sections
        policy.sections.all().delete()
        
        sections = [
            {
                'heading': '1. Acceptance of Terms',
                'content': 'These Terms of Use ("Terms") constitute a legally binding agreement between you (the "User," "you," or "your") and GNX Soft Ltd ("GNX," "we," "us," or "our"), a company registered in Bulgaria, governing your access to and use of our enterprise software solutions, websites, applications, and related services (collectively, the "Services"). By accessing, registering for, or using our Services, you acknowledge that you have read, understood, and agree to be bound by these Terms. If you do not agree to these Terms, you must not access or use our Services. For enterprise customers, these Terms supplement any Master Service Agreement or similar contract executed between your organization and GNX Soft Ltd.',
                'order': 1
            },
            {
                'heading': '2. Service Description and Scope',
                'content': 'GNX Soft Ltd provides enterprise software development, consulting, system integration, cloud services, and technical support solutions to clients across Defense & Aerospace, Healthcare & Medical, Telecommunication, E-commerce, Enterprise, Banking, Public Sector, Food & Beverages, and Oil & Energy industries. Our Services include but are not limited to: (a) Custom Software Development: Tailored enterprise applications and solutions for specific industry requirements; (b) Cloud Services: Hosting, infrastructure management, and cloud migration; (c) System Integration: Integration with existing enterprise systems and third-party platforms; (d) Consulting Services: Technical consulting, architecture design, and strategic advisory; (e) Support Services: Technical support, maintenance, and troubleshooting; (f) Training: User training, documentation, and knowledge transfer. Service specifications, features, and availability may vary based on your subscription tier and service agreement. We reserve the right to modify, enhance, or discontinue any aspect of our Services with reasonable notice.',
                'order': 2
            },
            {
                'heading': '3. User Accounts and Registration',
                'content': 'To access certain Services, you must create an account by providing accurate and complete information: (a) Eligibility: You must be at least 18 years old and have the authority to enter into these Terms; (b) Account Information: You agree to provide accurate, current, and complete information during registration; (c) Account Security: You are responsible for maintaining the confidentiality of your account credentials; (d) Authorized Use: You must not share account credentials or allow unauthorized access to your account; (e) Notification: You must notify us immediately of any unauthorized access or security breach; (f) Account Verification: We may require identity verification for certain account actions; (g) Multiple Accounts: You may not create multiple accounts without authorization. You are fully responsible for all activities conducted through your account.',
                'order': 3
            },
            {
                'heading': '4. Acceptable Use Policy',
                'content': 'You agree to use our Services only for lawful purposes and in accordance with these Terms. Prohibited activities include: (a) Legal Violations: Using Services for any illegal purpose or in violation of applicable laws; (b) Unauthorized Access: Attempting to gain unauthorized access to systems, networks, or accounts; (c) Security Breaches: Attempting to probe, scan, or test system vulnerabilities; (d) Malicious Code: Introducing viruses, malware, or other harmful code; (e) Service Disruption: Interfering with or disrupting Services or servers; (f) Reverse Engineering: Decompiling, disassembling, or reverse engineering our software; (g) Data Scraping: Using automated systems to extract data without authorization; (h) Impersonation: Impersonating any person or entity; (i) Intellectual Property: Infringing on intellectual property rights; (j) Spam: Sending unsolicited communications or spam. Violations may result in immediate account suspension or termination.',
                'order': 4
            },
            {
                'heading': '5. Intellectual Property Rights',
                'content': 'All intellectual property rights in the Services remain the property of GNX: (a) Ownership: GNX owns all rights, title, and interest in the Services, including software, technology, content, and documentation; (b) License Grant: Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable license to access and use our Services; (c) Restrictions: You may not copy, modify, distribute, sell, or lease any part of our Services; (d) Custom Developments: Ownership of custom developments is governed by your service agreement; (e) Client Data: You retain ownership of your data submitted to our Services; (f) Feedback: Any feedback, suggestions, or ideas you provide may be used by GNX without obligation; (g) Trademarks: All trademarks, logos, and service marks are property of their respective owners. Unauthorized use of our intellectual property is strictly prohibited.',
                'order': 5
            },
            {
                'heading': '6. Service Level Agreements',
                'content': 'Service availability and performance guarantees are defined in applicable Service Level Agreements (SLAs): (a) Enterprise SLAs: Enterprise customers have specific SLA terms in their service agreements; (b) Standard Terms: Standard service availability targets apply to all other users; (c) Uptime Commitment: We strive for 99.9% uptime for production services (excluding scheduled maintenance); (d) Maintenance Windows: Scheduled maintenance is performed during pre-announced windows; (e) Emergency Maintenance: May be performed with minimal notice for critical issues; (f) Performance Monitoring: We continuously monitor service performance and availability; (g) Service Credits: Eligible customers may receive service credits for SLA breaches as defined in their agreements; (h) Exclusions: SLAs do not apply to issues caused by factors outside our control.',
                'order': 6
            },
            {
                'heading': '7. Payment Terms and Billing',
                'content': 'If you purchase Services, you agree to the following payment terms: (a) Fees: You agree to pay all applicable fees according to your subscription plan or service agreement; (b) Payment Methods: We accept payment via credit card, wire transfer, or other approved methods; (c) Billing Cycle: Fees are billed according to your selected billing cycle (monthly, annually); (d) Automatic Renewal: Subscriptions automatically renew unless cancelled before renewal date; (e) Price Changes: We may change fees with 30 days notice; (f) Taxes: You are responsible for all applicable taxes; (g) Late Payment: Late payments may incur interest and service suspension; (h) Refunds: Fees are generally non-refundable except as required by law or specified in your service agreement; (i) Disputes: Payment disputes must be raised within 30 days of billing date.',
                'order': 7
            },
            {
                'heading': '8. Term and Termination',
                'content': 'These Terms remain in effect until terminated: (a) Duration: Terms continue for as long as you access or use our Services; (b) User Termination: You may terminate by closing your account and ceasing use of Services; (c) GNX Termination: We may suspend or terminate your access for Terms violations, non-payment, or at our discretion; (d) Notice: We will provide reasonable notice before termination except for material breaches; (e) Effect of Termination: Upon termination, your license to use Services ceases immediately; (f) Data Retrieval: You have 30 days to retrieve your data after termination; (g) Surviving Provisions: Provisions regarding intellectual property, liability, and disputes survive termination; (h) Enterprise Agreements: Termination provisions in service agreements supersede these general terms.',
                'order': 8
            },
            {
                'heading': '9. Disclaimer of Warranties',
                'content': 'TO THE MAXIMUM EXTENT PERMITTED BY LAW, SERVICES ARE PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND: (a) No Warranties: We disclaim all warranties, express or implied, including merchantability, fitness for particular purpose, and non-infringement; (b) Service Availability: We do not warrant uninterrupted, secure, or error-free operation; (c) Accuracy: We do not warrant accuracy, completeness, or reliability of content; (d) Third-Party Services: We are not responsible for third-party services or integrations; (e) Enterprise Warranties: Specific warranties for enterprise customers are defined in service agreements. Some jurisdictions do not allow warranty exclusions, so some limitations may not apply to you.',
                'order': 9
            },
            {
                'heading': '10. Limitation of Liability',
                'content': 'TO THE MAXIMUM EXTENT PERMITTED BY LAW: (a) Exclusion: GNX shall not be liable for indirect, incidental, special, consequential, or punitive damages; (b) Liability Cap: Total liability shall not exceed fees paid by you in the 12 months preceding the claim; (c) Business Losses: We are not liable for loss of profits, revenue, business, data, or goodwill; (d) Force Majeure: We are not liable for failures beyond our reasonable control; (e) Enterprise Agreements: Liability provisions in service agreements may differ; (f) Indemnification: You agree to indemnify GNX against claims arising from your use of Services or Terms violations. Some jurisdictions do not allow liability limitations, so some limitations may not apply to you.',
                'order': 10
            },
            {
                'heading': '11. Dispute Resolution and Governing Law',
                'content': 'These Terms are governed by the laws of the Republic of Bulgaria and the European Union, without regard to conflict of law provisions: (a) Governing Law: Bulgarian law and EU regulations (including GDPR) govern interpretation and enforcement; (b) Informal Resolution: Parties agree to attempt informal resolution through good faith negotiations before formal proceedings; (c) Mediation: Parties may agree to resolve disputes through mediation under Bulgarian Chamber of Commerce and Industry rules; (d) Jurisdiction: Disputes shall be subject to the exclusive jurisdiction of the competent courts of Burgas, Bulgaria; (e) EU Consumer Rights: EU consumers retain all rights under applicable consumer protection legislation; (f) Injunctive Relief: Either party may seek injunctive relief in competent Bulgarian courts; (g) Legal Costs: Recovery of legal costs determined according to Bulgarian Civil Procedure Code; (h) Enterprise Disputes: Dispute resolution in service agreements supersedes these provisions; (i) GDPR Compliance: All dispute resolution procedures comply with GDPR data protection requirements.',
                'order': 11
            },
            {
                'heading': '12. Modifications to Terms',
                'content': 'We reserve the right to modify these Terms at any time: (a) Notification: Material changes will be communicated via email, website notice, or in-app notification; (b) Effective Date: Changes become effective 30 days after notification (unless otherwise specified); (c) Continued Use: Continued use after changes constitute acceptance; (d) Objection: If you object to changes, you must discontinue use; (e) Enterprise Customers: Material changes to enterprise agreements require mutual consent; (f) Version History: Previous versions available upon request. We encourage regular review of these Terms.',
                'order': 12
            },
            {
                'heading': '13. General Provisions',
                'content': 'Additional terms: (a) Entire Agreement: These Terms constitute the entire agreement between parties; (b) Severability: Invalid provisions shall not affect remaining provisions in accordance with Bulgarian law; (c) Waiver: Failure to enforce any provision does not constitute waiver; (d) Assignment: You may not assign rights without written consent; we may assign without restriction subject to GDPR requirements; (e) Force Majeure: Neither party liable for delays due to circumstances beyond reasonable control as defined by Bulgarian law; (f) Independent Contractors: Parties are independent contractors, not partners or joint venturers; (g) Notices: Legal notices sent to email addresses on file; (h) Export Compliance: Services subject to EU export controls and regulations; (i) Public Sector Users: Public sector users subject to applicable Bulgarian and EU public procurement regulations; (j) Language: English version controls in case of translation conflicts; Bulgarian version available upon request; (k) GDPR Compliance: All provisions interpreted in accordance with GDPR and Bulgarian Personal Data Protection Act.',
                'order': 13
            },
            {
                'heading': '14. Contact Information',
                'content': 'For questions regarding these Terms, contact us: GNX Soft Ltd | Registered Address: Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria | Email: legal@gnxsoft.com | Phone: +359 896 13 80 30 | Business Inquiries: sales@gnxsoft.com | Support: support@gnxsoft.com | Website: https://gnxsoft.com | Business Hours: Monday-Friday, 9:00 AM - 6:00 PM EET. We will respond to inquiries within 5 business days.',
                'order': 14
            },
        ]
        
        for section_data in sections:
            PolicySection.objects.create(policy=policy, **section_data)
        
        self.stdout.write(self.style.SUCCESS(f'Created/Updated Terms of Use with {len(sections)} sections'))

    def create_support_policy(self):
        policy, created = Policy.objects.update_or_create(
            type='support',
            defaults={
                'title': 'Support Policy',
                'description': 'Our comprehensive support services and commitments',
                'version': '2.1',
                'effective_date': timezone.now().date(),
            }
        )
        
        # Clear existing sections
        policy.sections.all().delete()
        
        sections = [
            {
                'heading': '1. Support Overview and Commitment',
                'content': 'GNX Soft Ltd is committed to providing world-class technical support to ensure the success of our customers across Defense & Aerospace, Healthcare & Medical, Telecommunication, E-commerce, Enterprise, Banking, Public Sector, Food & Beverages, and Oil & Energy industries. This Support Policy outlines the terms, conditions, and service levels for our technical support services. Our support team consists of experienced engineers, certified specialists, and domain experts dedicated to resolving your technical issues and answering your questions promptly and professionally. Support services are available to all customers with active service agreements, with service levels varying based on subscription tier and contractual commitments. Our goal is to minimize downtime, maximize productivity, and ensure you derive maximum value from our enterprise solutions.',
                'order': 1
            },
            {
                'heading': '2. Support Coverage and Eligibility',
                'content': 'Support services are provided to eligible users under the following terms: (a) Active Subscription: Valid, current subscription or service agreement required; (b) Licensed Users: Support available to authorized users designated in service agreement; (c) Production Environments: Full support for production deployments across all supported industries; (d) Development/Testing: Limited support for non-production environments; (e) Current Versions: Full support for current and N-1 versions (previous major release); (f) Legacy Versions: Limited support or upgrade-only support for older versions; (g) Custom Developments: Support scope defined in project agreements; (h) Third-Party Integrations: Best-effort support for authorized integrations; (i) Geographic Coverage: Global support with regional expertise from Bulgaria (EU) and international partners. Enterprise customers may have enhanced coverage terms in their service agreements.',
                'order': 2
            },
            {
                'heading': '3. Support Channels and Access Methods',
                'content': 'We offer multiple channels for accessing support services: (a) Support Center: Primary channel via our web-based support portal (https://gnxsoft.com/support-center) for ticket submission, tracking, and knowledge base access; (b) Email Support: Available at support@gnxsoft.com for all support tiers; (c) Phone Support: Direct hotline access at +359 896 13 80 30 for Premium and Enterprise customers; (d) Live Chat: Real-time chat support during business hours for active issues; (e) Emergency Hotline: 24/7 emergency support for Critical issues (Enterprise only); (f) On-Site Support: Available for Enterprise customers per service agreement; (g) Remote Access: Secure remote assistance with customer authorization; (h) Community Forums: Peer-to-peer support and discussions. We recommend using the Support Center as the primary channel for optimal tracking and documentation.',
                'order': 3
            },
            {
                'heading': '4. Business Hours and Availability',
                'content': 'Support availability varies by service tier: (a) Standard Support Hours: Monday-Friday, 9:00 AM - 6:00 PM Eastern European Time (EET), excluding Bulgarian national holidays; (b) Extended Support Hours: Monday-Friday, 7:00 AM - 9:00 PM EET, Saturday 10:00 AM - 4:00 PM EET (Premium tier); (c) 24/7 Support: Round-the-clock support for Critical issues (Enterprise tier); (d) Regional Coverage: Local language support in major regions during business hours; (e) Holiday Schedule: Reduced coverage during Bulgarian and major European holidays with advance notice; (f) After-Hours Support: Available for Enterprise customers per SLA; (g) Follow-the-Sun Support: Global coverage for Enterprise customers with international operations; (h) Emergency Response: Critical issues receive immediate attention regardless of time. Business hours are specified in service agreements.',
                'order': 4
            },
            {
                'heading': '5. Priority Levels and Response Times',
                'content': 'Support requests are categorized by severity with corresponding response time commitments: (a) CRITICAL (P1): System down, major functionality completely unavailable, security breach, or data loss. Production environment severely impacted. Response: 1 hour (24/7 for Enterprise), Resolution target: 4 hours; (b) HIGH (P2): Major feature not functioning, significant performance degradation, or workaround available. Substantial business impact. Response: 4 business hours, Resolution target: 1 business day; (c) MEDIUM (P3): Minor feature issue, moderate inconvenience, workaround available. Limited business impact. Response: 8 business hours, Resolution target: 3 business days; (d) LOW (P4): General questions, feature requests, cosmetic issues, documentation. Minimal business impact. Response: 1 business day, Resolution target: 5 business days. Response times measured from ticket submission during business hours. Enterprise SLAs may have enhanced response commitments.',
                'order': 5
            },
            {
                'heading': '6. Support Request Submission Requirements',
                'content': 'To ensure efficient issue resolution, support requests should include: (a) Clear Description: Detailed explanation of the issue or question; (b) Impact Assessment: Business impact and urgency justification; (c) Steps to Reproduce: Detailed steps to replicate the issue; (d) Environment Information: System version, configuration, operating system, browser; (e) Error Messages: Complete error messages, log excerpts, and error codes; (f) Screenshots/Videos: Visual documentation of the issue when applicable; (g) Expected vs. Actual Behavior: What should happen vs. what is happening; (h) Recent Changes: Any recent changes to system, configuration, or data; (i) Affected Users: Number and types of users impacted; (j) Workarounds Attempted: Solutions already tried. Well-documented requests receive faster resolution. Our support team may request additional information during investigation.',
                'order': 6
            },
            {
                'heading': '7. Support Scope and Covered Activities',
                'content': 'Our support services include: (a) Troubleshooting: Diagnosis and resolution of technical issues; (b) Bug Fixes: Resolution of software defects in current versions; (c) Configuration Assistance: Help with system configuration and settings; (d) Usage Guidance: Instruction on feature usage and best practices; (e) Integration Support: Assistance with authorized system integrations; (f) Performance Optimization: Guidance on performance tuning; (g) Security Issues: Resolution of security vulnerabilities; (h) Documentation: Access to technical documentation and knowledge base; (i) Version Updates: Assistance with updates and patches; (j) Account Management: Help with account administration and user management. Support does not include custom development, data migration, extensive training, or services outside the standard product scope unless contracted separately.',
                'order': 7
            },
            {
                'heading': '8. Exclusions and Limitations',
                'content': 'Support services do not cover: (a) Custom Development: Bespoke coding, feature development, or customizations beyond product capabilities; (b) Data Migration: Large-scale data migration or transformation projects; (c) Third-Party Issues: Problems with third-party software, systems, or services not authorized by GNX; (d) Unsupported Configurations: Configurations not approved or documented by GNX; (e) Modified Software: Systems altered or customized by unauthorized parties; (f) End-User Training: Comprehensive training programs (available separately); (g) Network/Infrastructure: Customer network, hardware, or infrastructure issues; (h) Expired Licenses: Systems with expired or invalid licenses; (i) Legacy Versions: Versions beyond support lifecycle; (j) Misuse: Issues resulting from misuse, abuse, or negligence. These services may be available through professional services agreements.',
                'order': 8
            },
            {
                'heading': '9. Escalation Procedures',
                'content': 'If you are not satisfied with support response or resolution: (a) Technical Escalation: Request escalation to senior support engineer or technical lead; (b) Management Escalation: Contact support manager for service concerns; (c) Enterprise Account Manager: Enterprise customers can contact designated account managers; (d) Support Supervisor: Request supervisor review for process concerns; (e) Executive Escalation: For unresolved critical issues, contact support director; (f) Escalation Timing: Automatic escalation for tickets exceeding SLA targets; (g) Priority Re-evaluation: Request priority adjustment with business justification; (h) Status Updates: Regular updates provided during escalated issues; (i) Root Cause Analysis: Detailed RCA provided for critical incidents upon request. Escalation contacts are provided in your welcome materials and service agreements.',
                'order': 9
            },
            {
                'heading': '10. Knowledge Base and Self-Service Resources',
                'content': 'We provide comprehensive self-service resources: (a) Knowledge Base: Extensive library of articles, guides, and FAQs covering common issues and best practices; (b) Video Tutorials: Step-by-step video guides for key features and configurations; (c) Documentation: Complete technical documentation, API references, and user manuals; (d) Release Notes: Detailed information about updates, new features, and bug fixes; (e) System Status: Real-time status dashboard showing service health and incidents; (f) Community Forums: Peer-to-peer support, discussions, and shared solutions; (g) Webinars: Regular training webinars on features and best practices; (h) Developer Resources: Code samples, integration guides, and development tools; (i) Search Functionality: Advanced search across all resources. We encourage users to search the knowledge base before submitting tickets for faster resolution.',
                'order': 10
            },
            {
                'heading': '11. Customer Responsibilities',
                'content': 'Customers are expected to: (a) Cooperation: Provide necessary information, access, and cooperation for troubleshooting; (b) Timely Response: Respond promptly to support team requests for information; (c) Accurate Information: Ensure information provided is accurate and complete; (d) Authorized Users: Ensure only authorized users contact support; (e) Environment Maintenance: Maintain supported configurations and versions; (f) Backup Systems: Maintain adequate backup and disaster recovery procedures; (g) Security: Implement and maintain appropriate security measures; (h) Testing: Test changes in non-production environments when possible; (i) Documentation Review: Review documentation and knowledge base before contacting support; (j) Change Notification: Notify GNX of significant environment changes. Failure to meet these responsibilities may impact support effectiveness and response times.',
                'order': 11
            },
            {
                'heading': '12. Scheduled Maintenance and Updates',
                'content': 'We perform regular maintenance to ensure optimal service: (a) Scheduled Maintenance: Planned maintenance during announced windows (typically weekends/off-hours); (b) Advance Notice: Minimum 7 days notice for standard maintenance, 72 hours for urgent maintenance; (c) Maintenance Windows: Standard windows defined in SLA (e.g., Sunday 12:00 AM - 6:00 AM ET); (d) Emergency Maintenance: May be performed with minimal notice for critical security or stability issues; (e) Service Impact: We minimize service impact and provide advance impact assessments; (f) Communication: Maintenance notifications via email, support portal, and status dashboard; (g) Customer Scheduling: Enterprise customers may request specific maintenance windows; (h) Update Deployment: Regular feature updates, security patches, and bug fixes; (i) Testing: All changes thoroughly tested before production deployment; (j) Rollback Procedures: Immediate rollback capability for issues arising from maintenance.',
                'order': 12
            },
            {
                'heading': '13. Service Level Credits and Remedies',
                'content': 'For SLA breaches, eligible customers may receive: (a) Service Credits: Credits applied to future invoices as compensation for SLA violations; (b) Credit Calculation: Based on percentage of service unavailability or SLA violation severity; (c) Eligibility: Available to Enterprise and Premium customers with active SLAs; (d) Claim Process: Credits must be requested within 30 days of incident; (e) Documentation: Requires documentation of impact and SLA breach; (f) Maximum Credit: Annual credits capped at specified percentage of annual fees; (g) Exclusions: Credits not available for issues outside our control, scheduled maintenance, or customer-caused issues; (h) Alternative Remedies: Additional remedies may be specified in enterprise service agreements; (i) Priority Support: Temporary priority elevation for affected customers. Service credit terms are detailed in applicable SLAs and service agreements.',
                'order': 13
            },
            {
                'heading': '14. Feedback and Continuous Improvement',
                'content': 'We value your feedback and continuously improve our support services: (a) Satisfaction Surveys: Post-resolution surveys to rate support experience; (b) Feedback Channels: Multiple channels for providing feedback and suggestions; (c) Quality Monitoring: Regular monitoring and review of support interactions; (d) Performance Metrics: Tracking of response times, resolution rates, and customer satisfaction; (e) Training Programs: Ongoing training for support team members; (f) Process Improvement: Regular review and enhancement of support processes; (g) Feature Requests: Systematic evaluation of customer feature requests; (h) Quarterly Reviews: Business reviews for Enterprise customers; (i) Support Advisory Board: Customer input on support strategy and improvements. Your feedback directly influences our support service enhancements.',
                'order': 14
            },
            {
                'heading': '15. Contact Information and Resources',
                'content': 'Support Contact Information: GNX Soft Ltd | Company Address: Tsar Simeon I, 56, Burgas, Burgas 8000, Bulgaria | Support Portal: https://gnxsoft.com/support-center (preferred method) | Email: support@gnxsoft.com | Phone (Premium/Enterprise): +359 896 13 80 30 | Emergency Hotline (Enterprise): Available in your service agreement | Live Chat: Available in support portal during business hours | Business Hours: Monday-Friday, 9:00 AM - 6:00 PM EET. Enterprise Account Managers: Contact information provided in welcome materials. Additional Resources: Knowledge Base: kb.gnxsoft.com | Developer Portal: developers.gnxsoft.com | Community Forums: community.gnxsoft.com | System Status: status.gnxsoft.com | Training: training.gnxsoft.com. For industry-specific support inquiries (Defense & Aerospace, Healthcare & Medical, Telecommunication, E-commerce, Banking, Public Sector, Food & Beverages, Oil & Energy), please mention your industry sector when contacting support.',
                'order': 15
            },
        ]
        
        for section_data in sections:
            PolicySection.objects.create(policy=policy, **section_data)
        
        self.stdout.write(self.style.SUCCESS(f'Created/Updated Support Policy with {len(sections)} sections'))

