<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Handles plugin activation, deactivation, and DB table creation.
 */
class PBUAIV_Activator {

    // ── Activation ─────────────────────────────────────────────────────────────

    public static function activate() : void {
        if ( ! class_exists( 'WooCommerce' ) ) {
            deactivate_plugins( plugin_basename( PBUAIV_PLUGIN_FILE ) );
            wp_die(
                esc_html__( 'UAE VAT Invoice for WooCommerce requires WooCommerce to be installed and active.', 'pb-invoicing-system' ),
                esc_html__( 'Plugin Activation Error', 'pb-invoicing-system' ),
                [ 'back_link' => true ]
            );
        }

        self::create_tables();
        self::set_default_options();

        // Always reset onboarding flag so wizard runs after every (re-)activation
        update_option( 'pbuaiv_onboarding_done', false );

        // Flag for onboarding redirect
        set_transient( 'pbuaiv_activation_redirect', true, 30 );

        // Set DB version
        update_option( 'pbuaiv_db_version', PBUAIV_DB_VERSION );
    }

    // ── Deactivation ───────────────────────────────────────────────────────────

    public static function deactivate() : void {
        // Intentionally light — preserve data
    }

    // ── DB Tables ──────────────────────────────────────────────────────────────

    private static function create_tables() : void {
        global $wpdb;
        $charset = $wpdb->get_charset_collate();

        // Documents table — tracks every issued document
        $docs = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}pbuaiv_documents (
            id              BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            order_id        BIGINT(20) UNSIGNED NOT NULL,
            doc_type        VARCHAR(30)  NOT NULL DEFAULT 'invoice',
            doc_number      VARCHAR(60)  NOT NULL DEFAULT '',
            doc_date        DATE         NOT NULL,
            status          VARCHAR(20)  NOT NULL DEFAULT 'issued',
            pdf_path        VARCHAR(500) DEFAULT NULL,
            sent_at         DATETIME     DEFAULT NULL,
            created_at      DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at      DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY order_id (order_id),
            KEY doc_type (doc_type),
            KEY doc_number (doc_number),
            KEY status (status)
        ) $charset;";

        // Sequences table — per-document-type number sequences
        $seqs = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}pbuaiv_sequences (
            id          INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
            doc_type    VARCHAR(30)  NOT NULL,
            year        SMALLINT(4)  NOT NULL,
            next_number INT(11)      NOT NULL DEFAULT 1,
            PRIMARY KEY (id),
            UNIQUE KEY doc_year (doc_type, year)
        ) $charset;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $docs );
        dbDelta( $seqs );
    }

    // ── Default Options ────────────────────────────────────────────────────────

    private static function set_default_options() : void {
        $defaults = [
            'pbuaiv_company_name'        => get_bloginfo( 'name' ),
            'pbuaiv_company_address'     => '',
            'pbuaiv_company_city'        => '',
            'pbuaiv_company_emirate'     => 'Dubai',
            'pbuaiv_company_country'     => 'AE',
            'pbuaiv_company_phone'       => '',
            'pbuaiv_company_email'       => get_option( 'admin_email' ),
            'pbuaiv_company_website'     => site_url(),
            'pbuaiv_trn'                 => '',
            'pbuaiv_bank_name'           => '',
            'pbuaiv_bank_iban'           => '',
            'pbuaiv_bank_swift'          => '',
            'pbuaiv_bank_account'        => '',
            'pbuaiv_logo_id'             => 0,
            'pbuaiv_brand_primary'       => '#244b8e',
            'pbuaiv_brand_secondary'     => '#f59e0b',
            'pbuaiv_currency_aed_rate'   => '1',
            'pbuaiv_vat_rate'            => '5',
            'pbuaiv_default_template'    => 'modern',
            'pbuaiv_doc_language'        => 'en',
            'pbuaiv_invoice_prefix'      => 'INV-',
            'pbuaiv_invoice_suffix'      => '',
            'pbuaiv_invoice_padding'     => 4,
            'pbuaiv_invoice_reset'       => 'yearly',
            'pbuaiv_receipt_prefix'      => 'RCT-',
            'pbuaiv_receipt_suffix'      => '',
            'pbuaiv_receipt_padding'     => 4,
            'pbuaiv_receipt_reset'       => 'yearly',
            'pbuaiv_credit_note_prefix'  => 'CN-',
            'pbuaiv_credit_note_suffix'  => '',
            'pbuaiv_credit_note_padding' => 4,
            'pbuaiv_credit_note_reset'   => 'yearly',
            'pbuaiv_proforma_prefix'     => 'PRO-',
            'pbuaiv_proforma_suffix'     => '',
            'pbuaiv_proforma_padding'    => 4,
            'pbuaiv_proforma_reset'      => 'yearly',
            'pbuaiv_packing_slip_prefix' => 'PS-',
            'pbuaiv_packing_slip_suffix' => '',
            'pbuaiv_packing_slip_padding'=> 4,
            'pbuaiv_packing_slip_reset'  => 'yearly',
            'pbuaiv_delivery_note_prefix'=> 'DN-',
            'pbuaiv_delivery_note_suffix'=> '',
            'pbuaiv_delivery_note_padding'=> 4,
            'pbuaiv_delivery_note_reset' => 'yearly',
            'pbuaiv_auto_invoice_status' => [ 'processing' ],
            'pbuaiv_auto_receipt_status' => [ 'completed' ],
            'pbuaiv_auto_credit_note_status' => [ 'refunded' ],
            'pbuaiv_attach_invoice_emails' => [ 'customer_processing_order', 'customer_invoice' ],
            'pbuaiv_attach_receipt_emails' => [ 'customer_completed_order' ],
            'pbuaiv_attach_credit_note_emails' => [ 'customer_refunded_order' ],
            'pbuaiv_attach_proforma_emails' => [],
            'pbuaiv_customer_download'   => 'yes',
            'pbuaiv_guest_download'      => 'yes',
            'pbuaiv_pdf_engine'          => 'dompdf',
            'pbuaiv_paper_size'          => 'A4',
            'pbuaiv_onboarding_done'     => false,
        ];


        foreach ( $defaults as $key => $value ) {
            if ( get_option( $key ) === false ) {
                add_option( $key, $value );
            }
        }
    }
}
