<?php
/**
 * Plugin Installer
 *
 * @package Jeremias\WcLicensedProduct
 */

declare(strict_types=1);

namespace Jeremias\WcLicensedProduct;

/**
 * Handles plugin activation and deactivation
 */
final class Installer
{
    /**
     * Database table name for licenses
     */
    public const TABLE_LICENSES = 'wc_licensed_product_licenses';

    /**
     * Database table name for product versions
     */
    public const TABLE_PRODUCT_VERSIONS = 'wc_licensed_product_versions';

    /**
     * Run on plugin activation
     */
    public static function activate(): void
    {
        self::createTables();
        self::createCacheDir();

        // Set version in options
        update_option('wc_licensed_product_version', WC_LICENSED_PRODUCT_VERSION);

        // Register endpoints before flushing rewrite rules
        add_rewrite_endpoint('licenses', EP_ROOT | EP_PAGES);
        add_rewrite_endpoint('license-download', EP_ROOT | EP_PAGES);

        // Flush rewrite rules for REST API and My Account endpoints
        flush_rewrite_rules();
    }

    /**
     * Run on plugin deactivation
     */
    public static function deactivate(): void
    {
        // Clear scheduled cron events
        $timestamp = wp_next_scheduled('wclp_check_expiring_licenses');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'wclp_check_expiring_licenses');
        }

        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Create database tables
     */
    private static function createTables(): void
    {
        global $wpdb;

        $charsetCollate = $wpdb->get_charset_collate();

        $licensesTable = $wpdb->prefix . self::TABLE_LICENSES;
        $versionsTable = $wpdb->prefix . self::TABLE_PRODUCT_VERSIONS;

        $sqlLicenses = "CREATE TABLE {$licensesTable} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            license_key VARCHAR(64) NOT NULL,
            order_id BIGINT UNSIGNED NOT NULL,
            product_id BIGINT UNSIGNED NOT NULL,
            customer_id BIGINT UNSIGNED NOT NULL,
            domain VARCHAR(255) NOT NULL,
            version_id BIGINT UNSIGNED DEFAULT NULL,
            status ENUM('active', 'inactive', 'expired', 'revoked') NOT NULL DEFAULT 'active',
            activations_count INT UNSIGNED NOT NULL DEFAULT 0,
            max_activations INT UNSIGNED NOT NULL DEFAULT 1,
            expires_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),
            UNIQUE KEY license_key (license_key),
            KEY order_id (order_id),
            KEY product_id (product_id),
            KEY customer_id (customer_id),
            KEY domain (domain),
            KEY status (status)
        ) {$charsetCollate};";

        $sqlVersions = "CREATE TABLE {$versionsTable} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            product_id BIGINT UNSIGNED NOT NULL,
            version VARCHAR(32) NOT NULL,
            major_version INT UNSIGNED NOT NULL,
            minor_version INT UNSIGNED NOT NULL,
            patch_version INT UNSIGNED NOT NULL,
            release_notes TEXT DEFAULT NULL,
            download_url VARCHAR(512) DEFAULT NULL,
            attachment_id BIGINT UNSIGNED DEFAULT NULL,
            file_hash VARCHAR(64) DEFAULT NULL,
            download_count BIGINT UNSIGNED NOT NULL DEFAULT 0,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            released_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY product_version (product_id, version),
            KEY product_id (product_id),
            KEY major_version (major_version),
            KEY is_active (is_active)
        ) {$charsetCollate};";

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

    /**
     * Create Twig cache directory
     */
    private static function createCacheDir(): void
    {
        $cacheDir = WP_CONTENT_DIR . '/cache/wc-licensed-product/twig';
        if (!file_exists($cacheDir)) {
            wp_mkdir_p($cacheDir);
        }
    }

    /**
     * Get licenses table name
     */
    public static function getLicensesTable(): string
    {
        global $wpdb;
        return $wpdb->prefix . self::TABLE_LICENSES;
    }

    /**
     * Get product versions table name
     */
    public static function getVersionsTable(): string
    {
        global $wpdb;
        return $wpdb->prefix . self::TABLE_PRODUCT_VERSIONS;
    }
}
