<?php
defined('ABSPATH') || exit;

class IranDargah_Dashboard {
    
    private static $instance = null;
    private $plugin_url;
    private $plugin_path;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->plugin_url = plugin_dir_url(dirname(__FILE__));
        $this->plugin_path = plugin_dir_path(dirname(__FILE__));
        
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('admin_init', [$this, 'handle_settings_save']);
        
        require_once $this->plugin_path . 'admin/inc/settings-loader.php';
        require_once $this->plugin_path . 'admin/inc/rest-endpoints.php';
        require_once $this->plugin_path . 'admin/inc/gateway-cleanup.php';
        
        // Load reports dashboard
        require_once $this->plugin_path . 'admin/reports-dashboard.php';
    }
    
    public function add_admin_menu() {
        add_menu_page(
            __('Iranian Gateways', 'irandargah'),
            __('Iranian Gateways', 'irandargah'),
            'manage_options',
            'irandargah-dashboard',
            [$this, 'render_dashboard'],
            $this->get_menu_icon_svg(),
            30
        );
    }
    
    private function get_menu_icon_svg() {
        return 'data:image/svg+xml;base64,' . base64_encode('<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10 0C4.477 0 0 4.477 0 10s4.477 10 10 10 10-4.477 10-10S15.523 0 10 0zm0 18c-4.411 0-8-3.589-8-8s3.589-8 8-8 8 3.589 8 8-3.589 8-8 8zm-1-13v6l5.5 3.5L15 9l-4-2.5V5H9z" fill="currentColor"/></svg>');
    }
    
    public function enqueue_assets($hook) {
        if ('toplevel_page_irandargah-dashboard' !== $hook) {
            return;
        }
        
        wp_enqueue_style(
            'irandargah-dashboard',
            $this->plugin_url . 'admin/assets/css/dashboard.css',
            [],
            filemtime($this->plugin_path . 'admin/assets/css/dashboard.css')
        );
        
        wp_enqueue_script(
            'irandargah-dashboard',
            $this->plugin_url . 'admin/assets/js/dashboard.js',
            ['jquery'],
            filemtime($this->plugin_path . 'admin/assets/js/dashboard.js'),
            true
        );
        
        wp_localize_script('irandargah-dashboard', 'irandargahData', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'restUrl' => rest_url('irandargah/v1/'),
            'nonce' => wp_create_nonce('irandargah_dashboard_nonce'),
            'restNonce' => wp_create_nonce('wp_rest'),
            'strings' => [
                'saving' => __('در حال ذخیره...', 'irandargah'),
                'saved' => __('ذخیره شد', 'irandargah'),
                'error' => __('خطا در ذخیره‌سازی', 'irandargah'),
                'confirm' => __('آیا مطمئن هستید؟', 'irandargah'),
            ]
        ]);
    }
    
    public function handle_settings_save() {
        if (!isset($_POST['irandargah_save_settings']) || !wp_verify_nonce($_POST['irandargah_nonce'], 'irandargah_save')) {
            return;
        }
        
        if (!current_user_can('manage_options')) {
            wp_die(__('شما دسترسی لازم را ندارید.', 'irandargah'));
        }
        
        $gateway_id = sanitize_text_field($_POST['gateway_id'] ?? '');
        $settings = $_POST['settings'] ?? [];
        
        IranDargah_Settings_Loader::save_gateway_settings($gateway_id, $settings);
        
        wp_redirect(add_query_arg(['settings-updated' => '1'], admin_url('admin.php?page=irandargah-dashboard')));
        exit;
    }
    
    public function render_dashboard() {
        if (!current_user_can('manage_options')) {
            wp_die(__('شما دسترسی لازم را ندارید.', 'irandargah'));
        }
        
        $gateways = IranDargah_Settings_Loader::get_all_gateways_data();
        $current_theme = get_user_meta(get_current_user_id(), 'irandargah_theme', true) ?: 'light';
        
        ?>
        <div class="irandargah-dashboard-wrap" data-theme="<?php echo esc_attr($current_theme); ?>">
            <div class="irandargah-header">
                <div class="irandargah-header-content">
                    <h1 class="irandargah-title">
                        <svg class="irandargah-title-icon" width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M16 0C7.163 0 0 7.163 0 16s7.163 16 16 16 16-7.163 16-16S24.837 0 16 0zm0 29c-7.18 0-13-5.82-13-13S8.82 3 16 3s13 5.82 13 13-5.82 13-13 13zm-2-20v10l7 4.5L22 19l-6-3.75V9h-4z" fill="currentColor"/>
                        </svg>
                        <?php esc_html_e('درگاه‌های پرداخت ایران', 'irandargah'); ?>
                    </h1>
                    <div class="irandargah-header-actions">
                        <button class="irandargah-theme-toggle" aria-label="<?php esc_attr_e('تغییر تم', 'irandargah'); ?>">
                            <span class="theme-icon-light">☀️</span>
                            <span class="theme-icon-dark">🌙</span>
                        </button>
                    </div>
                </div>
            </div>
            
            <?php if (isset($_GET['settings-updated'])): ?>
                <div class="irandargah-notice irandargah-notice-success">
                    <span class="irandargah-notice-icon">✓</span>
                    <span class="irandargah-notice-message"><?php esc_html_e('تنظیمات با موفقیت ذخیره شد.', 'irandargah'); ?></span>
                </div>
            <?php endif; ?>
            
            <div class="irandargah-gateways-grid">
                <?php foreach ($gateways as $gateway): ?>
                    <div class="irandargah-gateway-card" data-gateway-id="<?php echo esc_attr($gateway['id']); ?>">
                        <div class="irandargah-gateway-card-header">
                            <div class="irandargah-gateway-icon">
                                <?php echo $gateway['icon']; ?>
                            </div>
                            <div class="irandargah-gateway-info">
                                <h2 class="irandargah-gateway-title"><?php echo esc_html($gateway['title']); ?></h2>
                                <p class="irandargah-gateway-description"><?php echo esc_html($gateway['description']); ?></p>
                            </div>
                            <div class="irandargah-gateway-toggle-wrapper">
                                <label class="irandargah-toggle">
                                    <input type="checkbox" 
                                           class="irandargah-toggle-input" 
                                           data-gateway-id="<?php echo esc_attr($gateway['id']); ?>"
                                           <?php checked($gateway['enabled'], 'yes'); ?>>
                                    <span class="irandargah-toggle-slider"></span>
                                </label>
                            </div>
                        </div>
                        
                        <div class="irandargah-gateway-status">
                            <span class="irandargah-status-badge <?php echo $gateway['enabled'] === 'yes' ? 'irandargah-status-active' : 'irandargah-status-inactive'; ?>">
                                <?php echo $gateway['enabled'] === 'yes' ? __('فعال', 'irandargah') : __('غیرفعال', 'irandargah'); ?>
                            </span>
                            <?php if ($gateway['sandbox'] === 'yes'): ?>
                                <span class="irandargah-sandbox-badge"><?php esc_html_e('حالت آزمایشی', 'irandargah'); ?></span>
                            <?php endif; ?>
                        </div>
                        
                        <div class="irandargah-gateway-actions">
                            <button class="irandargah-btn irandargah-btn-primary irandargah-settings-toggle" 
                                    data-gateway-id="<?php echo esc_attr($gateway['id']); ?>">
                                <span class="btn-icon">⚙️</span>
                                <?php esc_html_e('تنظیمات بیشتر', 'irandargah'); ?>
                            </button>
                        </div>
                        
                        <div class="irandargah-gateway-settings" id="settings-<?php echo esc_attr($gateway['id']); ?>" style="display: none;">
                            <form class="irandargah-settings-form" data-gateway-id="<?php echo esc_attr($gateway['id']); ?>" method="post" action="">
                                <?php wp_nonce_field('irandargah_save', 'irandargah_nonce'); ?>
                                <input type="hidden" name="irandargah_save_settings" value="1">
                                <input type="hidden" name="gateway_id" value="<?php echo esc_attr($gateway['id']); ?>">
                                
                                <div class="irandargah-settings-sections">
                                    <?php foreach ($gateway['settings_sections'] as $section_key => $section): ?>
                                        <div class="irandargah-settings-section">
                                            <h3 class="irandargah-section-title"><?php echo esc_html($section['title']); ?></h3>
                                            
                                            <?php foreach ($section['fields'] as $field_key => $field): ?>
                                                <div class="irandargah-form-group">
                                                    <label class="irandargah-label" for="<?php echo esc_attr($gateway['id'] . '_' . $field_key); ?>">
                                                        <?php echo esc_html($field['title']); ?>
                                                        <?php if (!empty($field['description'])): ?>
                                                            <span class="irandargah-help-tip" title="<?php echo esc_attr($field['description']); ?>">?</span>
                                                        <?php endif; ?>
                                                    </label>
                                                    
                                                    <?php if ($field['type'] === 'text' || $field['type'] === 'password'): ?>
                                                        <input type="<?php echo esc_attr($field['type']); ?>" 
                                                               id="<?php echo esc_attr($gateway['id'] . '_' . $field_key); ?>"
                                                               name="settings[<?php echo esc_attr($field_key); ?>]"
                                                               class="irandargah-input"
                                                               value="<?php echo esc_attr($field['value']); ?>"
                                                               placeholder="<?php echo esc_attr($field['placeholder'] ?? ''); ?>">
                                                    
                                                    <?php elseif ($field['type'] === 'textarea'): ?>
                                                        <textarea id="<?php echo esc_attr($gateway['id'] . '_' . $field_key); ?>"
                                                                  name="settings[<?php echo esc_attr($field_key); ?>]"
                                                                  class="irandargah-textarea"
                                                                  rows="4"><?php echo esc_textarea($field['value']); ?></textarea>
                                                    
                                                    <?php elseif ($field['type'] === 'checkbox'): ?>
                                                        <label class="irandargah-checkbox">
                                                            <input type="checkbox" 
                                                                   name="settings[<?php echo esc_attr($field_key); ?>]"
                                                                   value="yes"
                                                                   <?php checked($field['value'], 'yes'); ?>>
                                                            <span class="irandargah-checkbox-label"><?php echo esc_html($field['label'] ?? ''); ?></span>
                                                        </label>
                                                    
                                                    <?php elseif ($field['type'] === 'select'): ?>
                                                        <select id="<?php echo esc_attr($gateway['id'] . '_' . $field_key); ?>"
                                                                name="settings[<?php echo esc_attr($field_key); ?>]"
                                                                class="irandargah-select">
                                                            <?php foreach ($field['options'] as $opt_value => $opt_label): ?>
                                                                <option value="<?php echo esc_attr($opt_value); ?>" <?php selected($field['value'], $opt_value); ?>>
                                                                    <?php echo esc_html($opt_label); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    
                                                    <?php elseif ($field['type'] === 'readonly'): ?>
                                                        <div class="irandargah-readonly-field">
                                                            <code><?php echo esc_html($field['value']); ?></code>
                                                            <button type="button" class="irandargah-copy-btn" data-copy="<?php echo esc_attr($field['value']); ?>">
                                                                <?php esc_html_e('کپی', 'irandargah'); ?>
                                                            </button>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (!empty($field['description'])): ?>
                                                        <p class="irandargah-field-description"><?php echo esc_html($field['description']); ?></p>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                
                                <div class="irandargah-form-actions">
                                    <button type="submit" class="irandargah-btn irandargah-btn-success irandargah-save-btn">
                                        <span class="btn-icon">💾</span>
                                        <?php esc_html_e('ذخیره تنظیمات', 'irandargah'); ?>
                                    </button>
                                    <button type="button" class="irandargah-btn irandargah-btn-secondary irandargah-cancel-btn">
                                        <?php esc_html_e('انصراف', 'irandargah'); ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }
}

IranDargah_Dashboard::get_instance();


