<?php
/**
 * Handles plugin activation and deactivation.
 *
 * @package SkyEmagSync
 */

namespace SkyEmagSync;

defined( 'ABSPATH' ) || exit;

class Installer {

    /**
     * Run on plugin activation.
     */
    public static function activate(): void {
        self::create_tables();
        self::set_default_options();

        // Schedule cron if master switch is already on (edge case on re-activation).
        if ( Options::get( Options::MASTER_ENABLED ) ) {
            Sync\Scheduler::schedule();
        }

        // Daily log prune cron.
        if ( ! wp_next_scheduled( 'skyemag_log_prune' ) ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'skyemag_log_prune' );
        }

        flush_rewrite_rules();
    }

    /**
     * Run on plugin deactivation.
     */
    public static function deactivate(): void {
        Sync\Scheduler::unschedule();
        if ( class_exists( Sync\BuyButtonTracker::class ) ) {
            Sync\BuyButtonTracker::unschedule();
        }
        wp_clear_scheduled_hook( 'skyemag_log_prune' );
        flush_rewrite_rules();
    }

    /**
     * Lightweight upgrade: only ensures tables exist (safe for data).
     * Called from Plugin::maybe_upgrade_db() on version mismatch.
     */
    public static function upgrade_tables(): void {
        self::create_tables();
    }

    // ── Private helpers ──────────────────────────────────────────────────

    /**
     * Create or update custom tables via dbDelta.
     * Only runs dbDelta for tables that don't exist yet, to avoid any data loss
     * on hosting where dbDelta might behave unexpectedly.
     */
    private static function create_tables(): void {
        global $wpdb;

        $charset = $wpdb->get_charset_collate();

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        // ── Logs table ───────────────────────────────────────────────────
        $logs = $wpdb->prefix . 'skyemag_logs';
        dbDelta( "CREATE TABLE {$logs} (
            id          BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            created_at  DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
            product_id  BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            variation_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            action      VARCHAR(20)         NOT NULL DEFAULT '',
            result      VARCHAR(10)         NOT NULL DEFAULT '',
            message     TEXT,
            PRIMARY KEY (id),
            KEY idx_product   (product_id),
            KEY idx_created   (created_at)
        ) {$charset};" );

        // ── Categories cache table ───────────────────────────────────────
        $cats = $wpdb->prefix . 'skyemag_categories';
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$cats}'" ) !== $cats ) {
            dbDelta( "CREATE TABLE {$cats} (
                id               BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                emag_category_id INT UNSIGNED        NOT NULL,
                name             VARCHAR(500)        NOT NULL DEFAULT '',
                parent_id        INT UNSIGNED        NOT NULL DEFAULT 0,
                is_allowed       TINYINT(1)          NOT NULL DEFAULT 0,
                is_ean_mandatory TINYINT(1)          NOT NULL DEFAULT 0,
                is_warranty_mandatory TINYINT(1)     NOT NULL DEFAULT 0,
                characteristics  LONGTEXT,
                family_types     LONGTEXT,
                last_synced_at   DATETIME            DEFAULT NULL,
                PRIMARY KEY (id),
                UNIQUE KEY idx_emag_cat (emag_category_id),
                KEY idx_allowed (is_allowed)
            ) {$charset};" );
        }

        // ── Category map table ───────────────────────────────────────────
        $catmap = $wpdb->prefix . 'skyemag_category_map';
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$catmap}'" ) !== $catmap ) {
            dbDelta( "CREATE TABLE {$catmap} (
                id               BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                wc_category_id   BIGINT(20) UNSIGNED NOT NULL,
                emag_category_id INT UNSIGNED        NOT NULL,
                created_at       DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                UNIQUE KEY idx_wc_cat (wc_category_id),
                KEY idx_emag_cat (emag_category_id)
            ) {$charset};" );
        }

        // ── Characteristic map table (Step 3) ────────────────────────────
        $charmap = $wpdb->prefix . 'skyemag_characteristic_map';
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$charmap}'" ) !== $charmap ) {
            dbDelta( "CREATE TABLE {$charmap} (
                id               BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                emag_category_id INT UNSIGNED        NOT NULL,
                emag_char_id     INT UNSIGNED        NOT NULL,
                emag_char_name   VARCHAR(200)        NOT NULL DEFAULT '',
                wc_attribute     VARCHAR(200)        NOT NULL DEFAULT '',
                is_mandatory     TINYINT(1)          NOT NULL DEFAULT 0,
                default_value    VARCHAR(500)        DEFAULT NULL,
                PRIMARY KEY (id),
                UNIQUE KEY idx_cat_char (emag_category_id, emag_char_id),
                KEY idx_category (emag_category_id)
            ) {$charset};" );
        }

        // ── Family map table (Step 4) ────────────────────────────────────
        $fammap = $wpdb->prefix . 'skyemag_family_map';
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$fammap}'" ) !== $fammap ) {
            dbDelta( "CREATE TABLE {$fammap} (
                id                   BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                emag_category_id     INT UNSIGNED        NOT NULL,
                emag_family_type_id  INT UNSIGNED        NOT NULL,
                emag_family_name     VARCHAR(300)        NOT NULL DEFAULT '',
                wc_attribute         VARCHAR(200)        NOT NULL DEFAULT '',
                PRIMARY KEY (id),
                UNIQUE KEY idx_cat_fam (emag_category_id, emag_family_type_id),
                KEY idx_category (emag_category_id)
            ) {$charset};" );
        }

        // ── Margin history table (rollback feature) ──────────────────────
        $mhist = $wpdb->prefix . 'skyemag_margin_history';
        dbDelta( "CREATE TABLE {$mhist} (
            id         BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            product_id BIGINT(20) UNSIGNED NOT NULL,
            old_margin DECIMAL(7,2)        DEFAULT NULL,
            new_margin DECIMAL(7,2)        DEFAULT NULL,
            user_id    BIGINT(20) UNSIGNED DEFAULT NULL,
            changed_at DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_product (product_id),
            KEY idx_changed (changed_at)
        ) {$charset};" );

        update_option( 'skyemag_db_version', SKYEMAG_VERSION );
    }

    /**
     * Seed default option values (only if not already set).
     */
    private static function set_default_options(): void {
        $defaults = [
            Options::MASTER_ENABLED  => false,
            Options::GLOBAL_MARGIN   => 0.0,
            Options::ROUNDING_RULE   => 'none',
            Options::SYNC_SCHEDULE   => Options::DEFAULT_SCHEDULE,
            Options::API_CREDENTIALS => [],
        ];

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