<?php

class FacebookAdsInstaller
{
    public function install(): void
    {
        require_once __DIR__ . '/LicenseGuard.php';
        require_once __DIR__ . '/FbLang.php';
        $pdo = db();

        // ── إعدادات الإضافة ──────────────────────────────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_settings` (
                `id`              INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `access_token`    TEXT         DEFAULT NULL,
                `ad_account_id`   VARCHAR(100) DEFAULT NULL,
                `page_id`         VARCHAR(100) DEFAULT NULL,
                `pixel_id`        VARCHAR(100) DEFAULT NULL,
                `default_country` VARCHAR(10)  NOT NULL DEFAULT 'DZ',
                `default_currency`VARCHAR(10)  NOT NULL DEFAULT 'DZD',
                `is_active`       TINYINT(1)   NOT NULL DEFAULT 0,
                `license_domain`  VARCHAR(255) DEFAULT NULL,
                `license_key`     VARCHAR(128) DEFAULT NULL,
                `updated_at`      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── الحملات الإعلانية ─────────────────────────────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_campaigns` (
                `id`              INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `product_id`      INT UNSIGNED NOT NULL,
                `name`            VARCHAR(200) NOT NULL,
                `objective`       VARCHAR(50)  NOT NULL DEFAULT 'OUTCOME_SALES',
                `status`          ENUM('draft','pending','active','paused','deleted','error')
                                  NOT NULL DEFAULT 'draft',
                `daily_budget`    INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'in cents',
                `duration_days`   TINYINT UNSIGNED NOT NULL DEFAULT 7,
                `start_time`      DATETIME     DEFAULT NULL,
                `end_time`        DATETIME     DEFAULT NULL,
                `targeting`       JSON         NOT NULL,
                `ad_text`         TEXT         DEFAULT NULL,
                `ad_headline`     VARCHAR(255) DEFAULT NULL,
                `ad_description`  VARCHAR(255) DEFAULT NULL,
                `fb_campaign_id`  VARCHAR(100) DEFAULT NULL,
                `fb_adset_id`     VARCHAR(100) DEFAULT NULL,
                `fb_creative_id`  VARCHAR(100) DEFAULT NULL,
                `fb_ad_id`        VARCHAR(100) DEFAULT NULL,
                `error_message`   TEXT         DEFAULT NULL,
                `agent_id`        INT UNSIGNED DEFAULT NULL COMMENT 'NULL = manual, ID = AI agent',
                `ab_variant`      CHAR(1)      DEFAULT NULL COMMENT 'A/B/C testing variant',
                `impressions`     INT UNSIGNED DEFAULT 0,
                `reach`           INT UNSIGNED DEFAULT 0,
                `clicks`          INT UNSIGNED DEFAULT 0,
                `unique_clicks`   INT UNSIGNED DEFAULT 0,
                `spend`           DECIMAL(10,2) DEFAULT 0,
                `ctr`             DECIMAL(8,4)  DEFAULT 0,
                `cpc`             DECIMAL(10,2) DEFAULT 0,
                `cpm`             DECIMAL(10,2) DEFAULT 0,
                `frequency`       DECIMAL(6,2)  DEFAULT 0,
                `purchases`       INT UNSIGNED DEFAULT 0,
                `purchase_value`  DECIMAL(12,2) DEFAULT 0,
                `leads`           INT UNSIGNED DEFAULT 0,
                `last_sync`       DATETIME      DEFAULT NULL,
                `created_at`      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
                `updated_at`      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── إحصاءات تفصيلية ─────────────────────────────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_insights` (
                `id`             INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `campaign_id`    INT UNSIGNED NOT NULL,
                `date_start`     DATE         NOT NULL,
                `date_end`       DATE         NOT NULL,
                `impressions`    INT UNSIGNED DEFAULT 0,
                `clicks`         INT UNSIGNED DEFAULT 0,
                `reach`          INT UNSIGNED DEFAULT 0,
                `spend`          DECIMAL(10,2) DEFAULT 0,
                `ctr`            DECIMAL(6,4)  DEFAULT 0,
                `cpc`            DECIMAL(10,2) DEFAULT 0,
                `cpm`            DECIMAL(10,2) DEFAULT 0,
                `frequency`      DECIMAL(6,2)  DEFAULT 0,
                `purchases`      INT UNSIGNED DEFAULT 0,
                `add_to_cart`    INT UNSIGNED DEFAULT 0,
                `breakdown_type` VARCHAR(20)  DEFAULT NULL COMMENT 'age,gender,placement',
                `breakdown_value`VARCHAR(50)  DEFAULT NULL,
                `fetched_at`     TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
                KEY `idx_campaign` (`campaign_id`),
                KEY `idx_date` (`date_start`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── تقارير AI المحفوظة ────────────────────────────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_ai_reports` (
                `id`          INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `campaign_id` INT UNSIGNED DEFAULT NULL COMMENT 'NULL = overall report',
                `type`        ENUM('performance','suggestion','comparison') NOT NULL DEFAULT 'performance',
                `report`      MEDIUMTEXT   NOT NULL,
                `lang`        VARCHAR(10)  NOT NULL DEFAULT 'ar',
                `created_at`  TIMESTAMP    DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── إحصاءات تفصيلية يومية ─────────────────────────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_insights` (
                `id`             INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `campaign_id`    INT UNSIGNED NOT NULL,
                `date`           DATE         NOT NULL,
                `impressions`    INT UNSIGNED DEFAULT 0,
                `reach`          INT UNSIGNED DEFAULT 0,
                `clicks`         INT UNSIGNED DEFAULT 0,
                `spend`          DECIMAL(10,2) DEFAULT 0,
                `ctr`            DECIMAL(8,4)  DEFAULT 0,
                `cpc`            DECIMAL(10,2) DEFAULT 0,
                `cpm`            DECIMAL(10,2) DEFAULT 0,
                `frequency`      DECIMAL(6,2)  DEFAULT 0,
                `purchases`      INT UNSIGNED DEFAULT 0,
                `purchase_value` DECIMAL(12,2) DEFAULT 0,
                `leads`          INT UNSIGNED DEFAULT 0,
                `age_breakdown`  JSON          DEFAULT NULL,
                `gender_breakdown` JSON        DEFAULT NULL,
                `region_breakdown` JSON        DEFAULT NULL,
                `created_at`     TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY `uq_campaign_date` (`campaign_id`, `date`),
                KEY `idx_campaign` (`campaign_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── وكيل الإعلانات الذكي (Autonomous AI Agent) ──────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_agents` (
                `id`              INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `product_id`      INT UNSIGNED NOT NULL,
                `strategy_name`   VARCHAR(200) NOT NULL,
                `strategy_data`   LONGTEXT     NOT NULL COMMENT 'full AI strategy JSON',
                `monthly_budget`  DECIMAL(10,2) NOT NULL DEFAULT 0,
                `status`          ENUM('pending','active','paused','completed','error') NOT NULL DEFAULT 'pending',
                `lang`            VARCHAR(10)  NOT NULL DEFAULT 'ar',
                `launched_at`     DATETIME     DEFAULT NULL,
                `created_at`      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
                `updated_at`      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_agent_logs` (
                `id`         INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `agent_id`   INT UNSIGNED NOT NULL,
                `action`     VARCHAR(50)  NOT NULL COMMENT 'analyze|launch|optimize|pause',
                `data`       LONGTEXT     NOT NULL,
                `created_at` TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
                KEY `idx_agent` (`agent_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── جدول توصيات الذكاء الاصطناعي ────────────────────────
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `fb_ai_insights` (
                `id`          INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `campaign_id` INT UNSIGNED NOT NULL,
                `analysis`    LONGTEXT     NOT NULL,
                `score`       TINYINT UNSIGNED DEFAULT 0 COMMENT '0-100 performance score',
                `next_config` JSON         DEFAULT NULL COMMENT 'suggested next campaign config',
                `created_at`  TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
                KEY `idx_campaign` (`campaign_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // إعدادات افتراضية
        $check = $pdo->query("SELECT COUNT(*) FROM fb_settings")->fetchColumn();
        if ((int)$check === 0) {
            $pdo->exec("INSERT INTO fb_settings (default_country, default_currency) VALUES ('DZ', 'DZD')");
        }

        try { FbAdsLicenseGuard::bind(FbAdsLicenseGuard::currentDomain()); } catch (\Throwable $e) {}

        $this->mergeLangFiles();
        $this->patchProductsPage();
    }

    public function enable(): void
    {
        @require_once __DIR__ . '/LicenseGuard.php';
        @require_once __DIR__ . '/FbLang.php';
        $this->install(); // ensures tables exist on (re)enable
        $this->mergeLangFiles();
        $this->cleanOldMarkers();
        $this->patchSidebar();
        $this->patchProductsPage();
    }

    public function disable(): void {}

    private function mergeLangFiles(): void
    {
        $langDir    = ROOT_PATH . '/lang/';
        $pluginLang = __DIR__ . '/lang/';
        foreach (['en', 'ar'] as $code) {
            $src  = $pluginLang . $code . '.json';
            $dest = $langDir    . $code . '.json';
            if (!is_file($src) || !is_file($dest)) continue;
            $merged = array_merge(
                json_decode(file_get_contents($dest), true) ?? [],
                json_decode(file_get_contents($src),  true) ?? []
            );
            ksort($merged);
            file_put_contents($dest, json_encode($merged, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
    }

    private function cleanOldMarkers(): void
    {
        $headerPath = ROOT_PATH . '/admin/templates/header.php';
        if (!is_file($headerPath) || !is_writable($headerPath)) return;
        $content = file_get_contents($headerPath);
        if (!str_contains($content, '{{RC_SIDEBAR_HOOK}}')) return;
        $content = str_replace("{{RC_SIDEBAR_HOOK}}
", '', $content);
        $content = str_replace('{{RC_SIDEBAR_HOOK}}', '', $content);
        file_put_contents($headerPath, $content);
    }

    private function patchSidebar(): void
    {
        $headerPath = ROOT_PATH . '/admin/templates/header.php';
        if (!is_file($headerPath) || !is_writable($headerPath)) return;
        $content = file_get_contents($headerPath);
        $phpHook = "foreach (glob(ROOT_PATH . '/plugins/*/sidebar.php')";
        if (str_contains($content, $phpHook)) return;
        $needle = '<!-- ══ Logout ══ -->';
        if (!str_contains($content, $needle)) return;
        $hook = "\n                <?php foreach (glob(ROOT_PATH . '/plugins/*/sidebar.php') as \$_fbF) { @include \$_fbF; } ?>\n                ";
        file_put_contents($headerPath, str_replace($needle, $hook . $needle, $content));
    }

    private function patchProductsPage(): void
    {
        // products/index.php بالفعل يتحقق من PluginManager::isActive('SocialProductStudio')
        // سنضيف تحققاً مشابهاً لـ facebook-ads في نفس المنطقة
        $indexPath = ROOT_PATH . '/admin/templates/products/index.php';
        if (!is_file($indexPath) || !is_writable($indexPath)) return;
        $content = file_get_contents($indexPath);
        if (str_contains($content, "facebook-ads")) return;

        // أضف متغير التحقق بعد $socialStudioActive
        $old = '$socialStudioActive = PluginManager::isActive(\'SocialProductStudio\');';
        $new = '$socialStudioActive = PluginManager::isActive(\'SocialProductStudio\');' . "\n" .
               '$fbAdsActive = PluginManager::isActive(\'facebook-ads\');';
        $content = str_replace($old, $new, $content);

        // أضف الزر بعد زر social studio
        $oldBtn = '<?php endif; ?>' . "\n\n" .
                  '                                <a href="/admin/products/edit/';
        $newBtn = '<?php endif; ?>' . "\n" .
                  '                                <?php if ($fbAdsActive ?? false): ?>' . "\n" .
                  '                                <a href="/admin/facebook-ads/create/<?= (int)$product[\'id\'] ?>"' . "\n" .
                  '                                   class="btn btn-sm btn-outline-primary"' . "\n" .
                  '                                   title="<?= __(\'fb_ads.launch_ad\',\'Launch Facebook Ad\') ?>">' . "\n" .
                  '                                    <i class="bi bi-facebook"></i>' . "\n" .
                  '                                </a>' . "\n" .
                  '                                <?php endif; ?>' . "\n\n" .
                  '                                <a href="/admin/products/edit/';
        $content = str_replace($oldBtn, $newBtn, $content);
        file_put_contents($indexPath, $content);
    }
}
