<?php

/**
 * Plugin Name: به روز رسان پله
 * Plugin URI: https://pelle.agency
 * Description: پلاگین بروزرسانی قالب ماحامیتیم
 * Version: 1.0.0
 * Author: Pelle Agency
 * Author URI: https://pelle.agency
 * Text Domain: mahamitim-theme-updater
 * Domain Path: /languages
 * License: GPL v2 or later
 * Requires at least: 5.0
 * Tested up to: 6.4
 * Requires PHP: 7.4
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('PELLE_UPDATER_VERSION', '1.0.0');
define('PELLE_UPDATER_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('PELLE_UPDATER_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PELLE_UPDATER_PLUGIN_FILE', __FILE__);

/**
 * Main Plugin Class
 */
class MahamitimThemeUpdater
{
    /**
     * API Base URL
     */
    private $api_base_url = 'http://api.mahamitim.com/api';

    /**
     * Initialize the plugin
     */
    public function __construct()
    {
        add_action('init', array($this, 'load_textdomain'));
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_mahamitim_get_versions', array($this, 'ajax_get_versions'));
        add_action('wp_ajax_mahamitim_download_theme', array($this, 'ajax_download_theme'));
        add_action('wp_ajax_mahamitim_update_theme', array($this, 'ajax_update_theme'));
        add_action('wp_ajax_mahamitim_test_connection', array($this, 'ajax_test_connection'));
        add_action('wp_ajax_mahamitim_save_settings', array($this, 'ajax_save_settings'));
        add_action('wp_ajax_mahamitim_save_last_update', array($this, 'ajax_save_last_update'));
        add_action('wp_ajax_mahamitim_get_last_update', array($this, 'ajax_get_last_update'));
    }

    /**
     * Load text domain for translations
     */
    public function load_textdomain()
    {
        load_plugin_textdomain('mahamitim-theme-updater', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu()
    {
        add_menu_page(
            __('به روز رسان پله', 'mahamitim-theme-updater'),
            __('بروزرسانی قالب', 'mahamitim-theme-updater'),
            'manage_options',
            'mahamitim-theme-updater',
            array($this, 'admin_page'),
            'dashicons-update',
            30
        );
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook)
    {
        if ($hook !== 'toplevel_page_mahamitim-theme-updater') {
            return;
        }

        // Enqueue compiled Tailwind CSS
        wp_enqueue_style(
            'tailwindcss',
            PELLE_UPDATER_PLUGIN_URL . 'assets/css/tailwind.css',
            array(),
            PELLE_UPDATER_VERSION
        );

        wp_enqueue_script(
            'mahamitim-updater-admin',
            PELLE_UPDATER_PLUGIN_URL . 'assets/js/admin-new.js',
            array('jquery'),
            PELLE_UPDATER_VERSION,
            true
        );


        // Localize script
        wp_localize_script('mahamitim-updater-admin', 'mahamitimUpdater', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('PELLE_UPDATER_nonce'),
            'strings' => array(
                'loading' => __('در حال بارگذاری...', 'mahamitim-theme-updater'),
                'error' => __('خطا رخ داد', 'mahamitim-theme-updater'),
                'success' => __('عملیات با موفقیت انجام شد', 'mahamitim-theme-updater'),
                'confirmDownload' => __('آیا مطمئن هستید که می‌خواهید قالب را دانلود کنید؟', 'mahamitim-theme-updater'),
                'downloading' => __('در حال دانلود...', 'mahamitim-theme-updater'),
                'updating' => __('در حال بروزرسانی...', 'mahamitim-theme-updater'),
                'confirmUpdate' => __('آیا مطمئن هستید که می‌خواهید قالب را بروزرسانی کنید؟', 'mahamitim-theme-updater'),
                'connectionTest' => __('تست اتصال', 'mahamitim-theme-updater'),
                'connectionSuccess' => __('اتصال برقرار شد', 'mahamitim-theme-updater'),
                'connectionFailed' => __('اتصال برقرار نشد', 'mahamitim-theme-updater'),
            )
        ));
    }

    /**
     * Admin page HTML
     */
    public function admin_page()
    {
        $license_key = get_option('license_key', ''); // Read from standard WordPress license_key option
        $api_url = get_option('mahamitim_api_url', $this->api_base_url);
?>
        <div class="min-h-screen bg-gray-50 font-iranyekan" dir="rtl">
            <div class="flex">
                <!-- Navigation Sidebar -->
                <div class="hidden lg:flex lg:flex-shrink-0">
                    <div class="flex w-64 flex-col">
                        <div class="flex min-h-0 flex-1 flex-col border-r border-gray-200 bg-white">
                            <div class="flex h-16 flex-shrink-0 items-center border-b border-gray-200 px-4">
                                <div class="flex items-center gap-3 font-semibold">
                                    <div class="flex h-8 w-8 items-center justify-center rounded-lg bg-indigo-600 text-white">
                                        <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                        </svg>
                                    </div>
                                    <span class="text-lg text-gray-900"><?php _e('ماحامیتیم', 'mahamitim-theme-updater'); ?></span>
                                </div>
                            </div>
                            <div class="flex flex-1 flex-col overflow-y-auto pt-5 pb-4">
                                <nav class="mt-5 flex-1 space-y-1 bg-white px-2">
                                    <a href="#" class="bg-gray-100 text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md">
                                        <svg class="text-gray-500 ml-3 flex-shrink-0 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z" />
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m8 5l4-4 4 4" />
                                        </svg>
                                        <?php _e('داشبورد', 'mahamitim-theme-updater'); ?>
                                    </a>
                                    <a href="#" class="text-gray-600 hover:bg-gray-50 hover:text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md">
                                        <svg class="text-gray-400 ml-3 flex-shrink-0 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                        </svg>
                                        <?php _e('بروزرسانی قالب', 'mahamitim-theme-updater'); ?>
                                    </a>
                                    <a href="#" class="text-gray-400 cursor-not-allowed group flex items-center px-2 py-2 text-sm font-medium rounded-md opacity-50">
                                        <svg class="text-gray-400 ml-3 flex-shrink-0 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                                        </svg>
                                        <?php _e('بروزرسانی افزونه‌ها', 'mahamitim-theme-updater'); ?>
                                        <span class="mr-auto inline-flex items-center rounded-full bg-gray-200 px-2 py-1 text-xs font-medium text-gray-600"><?php _e('به زودی', 'mahamitim-theme-updater'); ?></span>
                                    </a>
                                    <a href="#" class="text-gray-400 cursor-not-allowed group flex items-center px-2 py-2 text-sm font-medium rounded-md opacity-50">
                                        <svg class="text-gray-400 ml-3 flex-shrink-0 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        </svg>
                                        <?php _e('تنظیمات', 'mahamitim-theme-updater'); ?>
                                        <span class="mr-auto inline-flex items-center rounded-full bg-gray-200 px-2 py-1 text-xs font-medium text-gray-600"><?php _e('به زودی', 'mahamitim-theme-updater'); ?></span>
                                    </a>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Main content -->
                <div class="flex flex-1 flex-col overflow-hidden">
                    <!-- Header -->
                    <header class="bg-white shadow">
                        <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8 flex items-center justify-between">
                            <div>
                                <h1 class="text-2xl font-bold text-gray-900"><?php _e('به روز رسان پله', 'mahamitim-theme-updater'); ?></h1>
                                <p class="text-sm text-gray-600 mt-1"><?php _e('دریافت آخرین نسخه قالب ماحامیتیم', 'mahamitim-theme-updater'); ?></p>
                            </div>
                            <div class="flex items-center gap-4">
                                <div id="connection-badge" class="inline-flex items-center rounded-full border border-gray-300 bg-yellow-50 px-3 py-1 text-xs font-medium text-yellow-800">
                                    <div class="mr-2 h-2 w-2 rounded-full bg-yellow-500"></div>
                                    <span id="connection-text"><?php _e('در حال بررسی اتصال', 'mahamitim-theme-updater'); ?></span>
                                </div>
                                <button type="button" id="refresh-connection" class="inline-flex items-center rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 cursor-pointer">
                                    <svg class="ml-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                    </svg>
                                    <?php _e('بروزرسانی', 'mahamitim-theme-updater'); ?>
                                </button>
                            </div>
                        </div>
                    </header>

                    <!-- Page Content -->
                    <main class="flex-1 overflow-y-auto">
                        <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
                            <div class="px-4 py-6 sm:px-0 space-y-6">
                                <!-- Stats Cards -->
                                <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                                    <div class="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
                                        <div class="flex items-center justify-between">
                                            <div>
                                                <h3 class="text-sm font-medium text-gray-600"><?php _e('آخرین بروزرسانی', 'mahamitim-theme-updater'); ?></h3>
                                                <div class="text-2xl font-bold text-gray-900 mt-1" id="stat-last-update"><?php _e('هرگز', 'mahamitim-theme-updater'); ?></div>
                                            </div>
                                            <div class="rounded-lg bg-green-50 p-3">
                                                <svg class="h-5 w-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                </svg>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
                                        <div class="flex items-center justify-between">
                                            <div>
                                                <h3 class="text-sm font-medium text-gray-600"><?php _e('وضعیت سیستم', 'mahamitim-theme-updater'); ?></h3>
                                                <div class="text-2xl font-bold text-gray-900 mt-1" id="stat-status"><?php _e('آماده', 'mahamitim-theme-updater'); ?></div>
                                            </div>
                                            <div class="rounded-lg bg-blue-50 p-3">
                                                <svg class="h-5 w-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                </svg>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
                                        <div class="flex items-center justify-between">
                                            <div>
                                                <h3 class="text-sm font-medium text-gray-600"><?php _e('نسخه فعلی', 'mahamitim-theme-updater'); ?></h3>
                                                <div class="text-2xl font-bold text-gray-900 mt-1" id="current-version"><?php _e('نامشخص', 'mahamitim-theme-updater'); ?></div>
                                            </div>
                                            <div class="rounded-lg bg-yellow-50 p-3">
                                                <svg class="h-5 w-5 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                                                </svg>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
                                        <div class="flex items-center justify-between">
                                            <div>
                                                <h3 class="text-sm font-medium text-gray-600"><?php _e('اتصال API', 'mahamitim-theme-updater'); ?></h3>
                                                <div class="text-2xl font-bold text-gray-900 mt-1" id="api-status"><?php _e('بررسی...', 'mahamitim-theme-updater'); ?></div>
                                            </div>
                                            <div class="rounded-lg bg-gray-50 p-3">
                                                <svg class="h-5 w-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                                                </svg>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <?php if (empty($license_key)): ?>
                                    <!-- License Warning -->
                                    <div class="rounded-lg border border-yellow-200 bg-yellow-50 p-6 shadow-sm">
                                        <div class="flex items-start gap-4">
                                            <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-yellow-100">
                                                <svg class="h-5 w-5 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                                                </svg>
                                            </div>
                                            <div class="flex-1">
                                                <h3 class="text-lg font-semibold text-yellow-900"><?php _e('هشدار لایسنس', 'mahamitim-theme-updater'); ?></h3>
                                                <p class="text-sm text-yellow-700 mt-1"><?php _e('کلید لایسنس یافت نشد. لطفاً ابتدا کلید لایسنس را در تنظیمات WordPress تنظیم کنید.', 'mahamitim-theme-updater'); ?></p>
                                                <div class="mt-4 rounded-md bg-yellow-100 border border-yellow-200 p-3">
                                                    <p class="text-sm text-yellow-800">
                                                        <?php _e('برای استفاده از امکانات بروزرسانی، ابتدا باید کلید لایسنس معتبر را در بخش تنظیمات عمومی WordPress وارد کنید.', 'mahamitim-theme-updater'); ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <!-- Main Update Interface -->
                                    <div class="rounded-lg border border-gray-200 bg-white shadow-sm">
                                        <div class="border-b border-gray-100 p-6">
                                            <div class="flex items-center justify-between">
                                                <div>
                                                    <h3 class="text-xl font-semibold text-gray-900"><?php _e('بروزرسانی قالب', 'mahamitim-theme-updater'); ?></h3>
                                                    <p class="text-sm text-gray-600 mt-1"><?php _e('آخرین نسخه را دریافت کنید یا نسخه مورد نظر خود را انتخاب کنید', 'mahamitim-theme-updater'); ?></p>
                                                </div>
                                                <div class="flex items-center gap-3">
                                                    <button type="button" id="refresh-versions" class="inline-flex items-center rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 cursor-pointer">
                                                        <svg class="ml-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                                        </svg>
                                                        <?php _e('بروزرسانی لیست', 'mahamitim-theme-updater'); ?>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="p-6">
                                            <div class="grid gap-6 lg:grid-cols-3">
                                                <!-- Quick Update -->
                                                <div class="lg:col-span-1">
                                                    <div class="rounded-lg border border-indigo-200 bg-indigo-50 p-4">
                                                        <div class="flex items-center mb-3">
                                                            <div class="flex h-8 w-8 items-center justify-center rounded-lg bg-indigo-600 text-white ml-3">
                                                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                                                </svg>
                                                            </div>
                                                            <h4 class="text-sm font-semibold text-indigo-900 !my-3"><?php _e('بروزرسانی سریع', 'mahamitim-theme-updater'); ?></h4>
                                                        </div>
                                                        <p class="text-xs text-indigo-700 mb-4"><?php _e('آخرین نسخه منتشر شده', 'mahamitim-theme-updater'); ?></p>
                                                        <button type="button" id="quick-update-btn" class="w-full inline-flex items-center justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 cursor-pointer">
                                                            <?php _e('آپدیت به آخرین نسخه', 'mahamitim-theme-updater'); ?>
                                                        </button>
                                                    </div>
                                                </div>

                                                <!-- Version Selection -->
                                                <div class="lg:col-span-2">
                                                    <div class="space-y-4">
                                                        <div>
                                                            <label for="theme_version" class="block text-sm font-medium text-gray-700 mb-2"><?php _e('انتخاب نسخه خاص:', 'mahamitim-theme-updater'); ?></label>
                                                            <select id="theme_version" class="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500">
                                                                <option value=""><?php _e('در حال بارگذاری...', 'mahamitim-theme-updater'); ?></option>
                                                            </select>
                                                            <p class="text-xs text-gray-500 mt-1">
                                                                <?php _e('برای دانلود نسخه خاص، ابتدا آن را انتخاب کنید', 'mahamitim-theme-updater'); ?>
                                                            </p>
                                                        </div>
                                                        <div class="flex gap-3">
                                                            <button type="button" id="update-theme" class="flex-1 inline-flex items-center justify-center rounded-md bg-green-600 px-3 py-2 text-sm font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer" disabled>
                                                                <svg class="ml-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                                                </svg>
                                                                <?php _e('آپدیت به نسخه انتخابی', 'mahamitim-theme-updater'); ?>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <!-- Hidden Settings Form -->
                                <form id="mahamitim-settings-form" class="hidden">
                                    <input type="url" id="api_url" name="api_url" value="<?php echo esc_attr($api_url); ?>" required>
                                </form>
                            </div>
                        </div>
                    </main>
                </div>
            </div>

            <!-- Update Progress Modal - Shadcn Style -->
            <div id="update-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
                <div class="flex min-h-screen items-center justify-center p-4 sm:p-6">
                    <!-- Backdrop -->
                    <div class="fixed inset-0 bg-black/80 transition-opacity"></div>

                    <!-- Modal -->
                    <div class="relative w-full max-w-2xl transform rounded-lg border bg-background p-0 shadow-lg transition-all">
                        <!-- Header -->
                        <div class="border-b px-6 py-4">
                            <div class="flex items-center justify-between">
                                <div class="space-y-1">
                                    <h3 class="text-lg font-semibold leading-none tracking-tight"><?php _e('در حال بروزرسانی قالب', 'mahamitim-theme-updater'); ?></h3>
                                    <p class="text-sm text-muted-foreground"><?php _e('لطفاً تا تکمیل فرآیند منتظر بمانید', 'mahamitim-theme-updater'); ?></p>
                                </div>
                                <button type="button" id="close-modal" class="hidden rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2">
                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                    <span class="sr-only">بستن</span>
                                </button>
                            </div>
                        </div>

                        <!-- Progress Content -->
                        <div class="space-y-6 p-6">
                            <!-- Progress Bar -->
                            <div class="space-y-3">
                                <div class="flex items-center justify-between text-sm">
                                    <span class="font-medium"><?php _e('پیشرفت', 'mahamitim-theme-updater'); ?></span>
                                    <span id="progress-percentage" class="text-muted-foreground">0%</span>
                                </div>
                                <div class="h-2 w-full rounded-full bg-secondary">
                                    <div id="progress-bar" class="h-2 rounded-full bg-primary transition-all duration-500 ease-out" style="width: 0%"></div>
                                </div>
                            </div>

                            <!-- Current Step -->
                            <div class="flex items-center space-x-2 space-x-reverse">
                                <div id="step-spinner" class="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
                                    <svg class="h-4 w-4 text-primary animate-spin" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                </div>
                                <div class="flex-1">
                                    <p id="current-step" class="text-sm font-medium"><?php _e('آماده‌سازی...', 'mahamitim-theme-updater'); ?></p>
                                </div>
                            </div>

                            <!-- Steps Log -->
                            <div class="space-y-2">
                                <h4 class="text-sm font-medium"><?php _e('جزئیات عملیات:', 'mahamitim-theme-updater'); ?></h4>
                                <div id="steps-log" class="max-h-48 space-y-2 overflow-y-auto rounded-md border bg-muted/30 p-3">
                                    <!-- Steps will be added here dynamically -->
                                </div>
                            </div>
                        </div>

                        <!-- Footer -->
                        <div class="border-t bg-muted/30 px-6 py-4">
                            <div class="flex justify-end">
                                <button type="button" id="modal-close-btn" class="hidden inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">
                                    <svg class="ml-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                    </svg>
                                    <?php _e('تکمیل شد', 'mahamitim-theme-updater'); ?>
                                </button>
                                <div id="modal-loading" class="flex items-center text-sm text-muted-foreground">
                                    <svg class="ml-2 h-4 w-4 animate-spin text-primary" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                    <?php _e('در حال پردازش...', 'mahamitim-theme-updater'); ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Toast Notifications -->
            <div id="toast-container" class="fixed bottom-4 left-4 z-50 space-y-3"></div>
        </div>
<?php
    }

    /**
     * Ajax handler for getting theme versions
     */
    public function ajax_get_versions()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $api_url = get_option('mahamitim_api_url', $this->api_base_url);

        $response = wp_remote_get($api_url . '/licenses/themes/versions/', array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'timeout' => 30,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => $response->get_error_message()));
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code !== 200) {
            wp_send_json_error(array(
                'message' => isset($data['error']) ? $data['error'] : __('خطا در دریافت اطلاعات', 'mahamitim-theme-updater')
            ));
        }

        wp_send_json_success($data);
    }

    /**
     * Ajax handler for downloading theme
     */
    public function ajax_download_theme()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $license_key = get_option('license_key', ''); // Read from standard WordPress license_key option
        $api_url = get_option('mahamitim_api_url', $this->api_base_url);
        $version = sanitize_text_field($_POST['version'] ?? '');

        if (empty($license_key)) {
            wp_send_json_error(array('message' => __('کلید لایسنس تنظیم نشده است', 'mahamitim-theme-updater')));
        }

        $payload = array('license_key' => $license_key);
        if (!empty($version)) {
            $payload['version'] = $version;
        }

        $response = wp_remote_post($api_url . '/licenses/themes/download/', array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($payload),
            'timeout' => 120,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => $response->get_error_message()));
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code !== 200) {
            wp_send_json_error(array(
                'message' => isset($data['error']) ? $data['error'] : __('خطا در دانلود قالب', 'mahamitim-theme-updater')
            ));
        }

        wp_send_json_success($data);
    }

    /**
     * Ajax handler for testing connection
     */
    public function ajax_test_connection()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $api_url = get_option('mahamitim_api_url', $this->api_base_url);

        $response = wp_remote_get($api_url . '/licenses/themes/versions/', array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => $response->get_error_message()));
        }

        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code === 200) {
            wp_send_json_success(array('message' => __('اتصال برقرار شد', 'mahamitim-theme-updater')));
        } else {
            wp_send_json_error(array('message' => __('اتصال برقرار نشد', 'mahamitim-theme-updater')));
        }
    }

    /**
     * Ajax handler for saving settings
     */
    public function ajax_save_settings()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $api_url = esc_url_raw($_POST['api_url'] ?? '');
        $license_key = sanitize_textarea_field($_POST['license_key'] ?? '');

        update_option('mahamitim_api_url', $api_url);
        // License key is now read-only from get_option('license_key')
        // update_option('mahamitim_license_key', $license_key);

        wp_send_json_success(array('message' => __('تنظیمات ذخیره شد', 'mahamitim-theme-updater')));
    }

    /**
     * Ajax handler for updating theme (download and install)
     */
    public function ajax_update_theme()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $license_key = get_option('license_key', ''); // Read from standard WordPress license_key option
        $api_url = get_option('mahamitim_api_url', $this->api_base_url);
        $version = sanitize_text_field($_POST['version'] ?? '');

        if (empty($license_key)) {
            wp_send_json_error(array('message' => __('کلید لایسنس تنظیم نشده است', 'mahamitim-theme-updater')));
        }

        // Step 1: Get download URL from API
        $this->log_progress(__('مرحله 1: درخواست لینک دانلود از API', 'mahamitim-theme-updater'));

        $payload = array('license_key' => $license_key);
        if (!empty($version)) {
            $payload['version'] = $version;
        }

        $response = wp_remote_post($api_url . '/licenses/themes/download/', array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($payload),
            'timeout' => 120,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => $response->get_error_message()));
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code !== 200) {
            wp_send_json_error(array(
                'message' => isset($data['error']) ? $data['error'] : __('خطا در دریافت لینک دانلود', 'mahamitim-theme-updater')
            ));
        }

        if (!isset($data['download_url'])) {
            wp_send_json_error(array('message' => __('لینک دانلود در پاسخ API یافت نشد', 'mahamitim-theme-updater')));
        }

        $download_url = $data['download_url'];
        $original_theme_name = isset($data['theme_name']) ? $data['theme_name'] : 'mahamitim-theme';

        // Step 2: Download the theme ZIP file
        $this->log_progress(__('مرحله 2: دانلود فایل ZIP قالب', 'mahamitim-theme-updater'));

        $temp_file = download_url($download_url, 300);

        if (is_wp_error($temp_file)) {
            wp_send_json_error(array('message' => __('خطا در دانلود فایل: ', 'mahamitim-theme-updater') . $temp_file->get_error_message()));
        }

        // Step 3: Extract ZIP file to wp-content/themes/
        $this->log_progress(__('مرحله 3: استخراج فایل ZIP به پوشه themes', 'mahamitim-theme-updater'));

        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();

        global $wp_filesystem;
        $themes_dir = WP_CONTENT_DIR . '/themes/';

        // Create a temporary extraction directory
        $extract_dir = $themes_dir . 'temp_' . uniqid();
        $wp_filesystem->mkdir($extract_dir);

        // Extract ZIP file
        $unzip_result = unzip_file($temp_file, $extract_dir);

        if (is_wp_error($unzip_result)) {
            // Cleanup
            $wp_filesystem->delete($temp_file);
            $wp_filesystem->rmdir($extract_dir, true);
            wp_send_json_error(array('message' => __('خطا در استخراج فایل: ', 'mahamitim-theme-updater') . $unzip_result->get_error_message()));
        }

        // Step 4: Find the theme folder and move it to correct location
        $this->log_progress(__('مرحله 4: انتقال فایل‌های قالب به مکان نهایی', 'mahamitim-theme-updater'));

        $extracted_files = $wp_filesystem->dirlist($extract_dir);
        $theme_folder_name = '';

        // Find the theme folder (usually the first directory)
        foreach ($extracted_files as $file_name => $file_info) {
            if ($file_info['type'] === 'd') {
                $theme_folder_name = $file_name;
                break;
            }
        }

        if (empty($theme_folder_name)) {
            // If no directory found, assume all files are in root and use original name
            $theme_folder_name = $original_theme_name;
            $source_dir = $extract_dir;
        } else {
            $source_dir = $extract_dir . '/' . $theme_folder_name;
        }

        // Use the extracted folder name as the final theme directory name
        $final_theme_name = $theme_folder_name;
        $destination_dir = $themes_dir . $final_theme_name;

        // Backup existing theme if it exists
        if ($wp_filesystem->exists($destination_dir)) {
            $this->log_progress(__('مرحله 4.1: پشتیبان‌گیری از قالب قبلی', 'mahamitim-theme-updater'));
            $backup_dir = $destination_dir . '_backup_' . date('Y-m-d_H-i-s');
            $wp_filesystem->move($destination_dir, $backup_dir);
        }

        // Move theme to final location
        $move_result = $wp_filesystem->move($source_dir, $destination_dir);

        if (!$move_result) {
            // Cleanup
            $wp_filesystem->delete($temp_file);
            $wp_filesystem->rmdir($extract_dir, true);
            wp_send_json_error(array('message' => __('خطا در انتقال فایل‌های قالب', 'mahamitim-theme-updater')));
        }

        // Step 5: Cleanup temporary files
        $this->log_progress(__('مرحله 5: پاک‌سازی فایل‌های موقت', 'mahamitim-theme-updater'));

        $wp_filesystem->delete($temp_file);
        $wp_filesystem->rmdir($extract_dir, true);

        // Step 6: Update WordPress theme cache
        $this->log_progress(__('مرحله 6: بروزرسانی کش قالب‌های WordPress', 'mahamitim-theme-updater'));

        // Refresh theme cache
        search_theme_directories(true);

        $this->log_progress(__('✅ بروزرسانی قالب با موفقیت تکمیل شد!', 'mahamitim-theme-updater'));

        wp_send_json_success(array(
            'message' => __('قالب با موفقیت بروزرسانی شد', 'mahamitim-theme-updater'),
            'theme_name' => $final_theme_name,
            'version' => $version ?: 'latest',
            'location' => '/wp-content/themes/' . $final_theme_name
        ));
    }

    /**
     * Ajax handler for saving last update data
     */
    public function ajax_save_last_update()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $update_data = sanitize_textarea_field($_POST['update_data'] ?? '');

        if (empty($update_data)) {
            wp_send_json_error(array('message' => __('داده‌های بروزرسانی خالی است', 'mahamitim-theme-updater')));
        }

        // Validate JSON
        $data = json_decode($update_data, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error(array('message' => __('فرمت داده‌های بروزرسانی نامعتبر است', 'mahamitim-theme-updater')));
        }

        // Save to WordPress options
        update_option('mahamitim_last_update_data', $data);
        update_option('mahamitim_last_update', current_time('mysql'));

        wp_send_json_success(array('message' => __('داده‌های بروزرسانی ذخیره شد', 'mahamitim-theme-updater')));
    }

    /**
     * Ajax handler for getting last update data
     */
    public function ajax_get_last_update()
    {
        check_ajax_referer('PELLE_UPDATER_nonce', 'nonce');

        $last_update_data = get_option('mahamitim_last_update_data', array());
        $last_update_time = get_option('mahamitim_last_update', '');

        if (empty($last_update_data) && empty($last_update_time)) {
            wp_send_json_success(array(
                'timestamp' => null,
                'data' => null,
                'message' => __('هیچ بروزرسانی یافت نشد', 'mahamitim-theme-updater')
            ));
        }

        // Use timestamp from data if available, otherwise use the option timestamp
        $timestamp = !empty($last_update_data['timestamp']) ? $last_update_data['timestamp'] : $last_update_time;

        wp_send_json_success(array(
            'timestamp' => $timestamp,
            'data' => $last_update_data,
            'mysql_time' => $last_update_time
        ));
    }

    /**
     * Helper function to log progress steps
     */
    private function log_progress($message)
    {
        // This would be called via AJAX to update the frontend
        // For now, we'll just log to error_log if WP_DEBUG is enabled
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mahamitim Theme Updater: ' . $message);
        }
    }
}

// Initialize the plugin
new MahamitimThemeUpdater();
