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

class IranDargah_Reports_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__));
        
        // Load settings loader for gateway data
        if (!class_exists('IranDargah_Settings_Loader')) {
            require_once $this->plugin_path . 'admin/inc/settings-loader.php';
        }
        
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('wp_ajax_irandargah_reports_data', [$this, 'ajax_get_reports_data']);
        add_action('wp_ajax_irandargah_transactions', [$this, 'ajax_get_transactions']);
        add_action('wp_ajax_irandargah_pending_payments', [$this, 'ajax_get_pending_payments']);
        add_action('wp_ajax_irandargah_fraud_detection', [$this, 'ajax_get_fraud_detection']);
    }
    
    public function add_admin_menu() {
        add_submenu_page(
            'irandargah-dashboard',
            __('گزارشات درگاه‌های ایرانی', 'irandargah'),
            __('گزارشات درگاه‌های ایرانی', 'irandargah'),
            'manage_options',
            'irandargah-reports',
            [$this, 'render_dashboard'],
            2
        );
    }
    
    public function enqueue_assets($hook) {
        if ('iranian-gateways_page_irandargah-reports' !== $hook) {
            return;
        }
        
        // Chart.js for analytics
        wp_enqueue_script(
            'chartjs',
            'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js',
            [],
            '4.4.0',
            true
        );
        
        // Date picker
        wp_enqueue_script('jquery-ui-datepicker');
        wp_enqueue_style('jquery-ui-datepicker', 'https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css');
        
        // Custom styles
        wp_enqueue_style(
            'irandargah-reports',
            $this->plugin_url . 'admin/assets/css/reports-dashboard.css',
            [],
            '1.0.0'
        );
        
        // Custom scripts
        wp_enqueue_script(
            'irandargah-reports',
            $this->plugin_url . 'admin/assets/js/reports-dashboard.js',
            ['jquery', 'chartjs', 'jquery-ui-datepicker'],
            '1.0.0',
            true
        );
        
        wp_localize_script('irandargah-reports', 'irandargahReports', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('irandargah_reports_nonce'),
            'strings' => [
                'loading' => __('در حال بارگذاری...', 'irandargah'),
                'error' => __('خطا در بارگذاری داده‌ها', 'irandargah'),
                'no_data' => __('داده‌ای یافت نشد', 'irandargah'),
            ]
        ]);
    }
    
    public function render_dashboard() {
        $current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'analytics';
        
        ?>
        <div class="irandargah-reports-wrap">
            <div class="irandargah-reports-header">
                <h1 class="irandargah-reports-title">
                    <span class="dashicons dashicons-chart-line"></span>
                    <?php esc_html_e('گزارشات درگاه‌های ایرانی', 'irandargah'); ?>
                </h1>
            </div>
            
            <div class="irandargah-reports-tabs">
                <a href="?page=irandargah-reports&tab=analytics" 
                   class="irandargah-tab <?php echo $current_tab === 'analytics' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-chart-bar"></span>
                    <?php esc_html_e('تحلیل‌های پیشرفته', 'irandargah'); ?>
                </a>
                <a href="?page=irandargah-reports&tab=alerts" 
                   class="irandargah-tab <?php echo $current_tab === 'alerts' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-warning"></span>
                    <?php esc_html_e('هشدارها و اطلاع‌رسانی', 'irandargah'); ?>
                </a>
                <a href="?page=irandargah-reports&tab=transactions" 
                   class="irandargah-tab <?php echo $current_tab === 'transactions' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-list-view"></span>
                    <?php esc_html_e('حسابرسی تراکنش‌ها', 'irandargah'); ?>
                </a>
                <a href="?page=irandargah-reports&tab=pending" 
                   class="irandargah-tab <?php echo $current_tab === 'pending' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-clock"></span>
                    <?php esc_html_e('پرداخت‌های معلق', 'irandargah'); ?>
                </a>
                <a href="?page=irandargah-reports&tab=fraud" 
                   class="irandargah-tab <?php echo $current_tab === 'fraud' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-shield"></span>
                    <?php esc_html_e('تشخیص تقلب', 'irandargah'); ?>
                </a>
                <a href="?page=irandargah-reports&tab=crm" 
                   class="irandargah-tab <?php echo $current_tab === 'crm' ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-networking"></span>
                    <?php esc_html_e('یکپارچگی CRM', 'irandargah'); ?>
                </a>
            </div>
            
            <div class="irandargah-reports-content">
                <?php
                switch ($current_tab) {
                    case 'analytics':
                        $this->render_analytics_tab();
                        break;
                    case 'alerts':
                        $this->render_alerts_tab();
                        break;
                    case 'transactions':
                        $this->render_transactions_tab();
                        break;
                    case 'pending':
                        $this->render_pending_tab();
                        break;
                    case 'fraud':
                        $this->render_fraud_tab();
                        break;
                    case 'crm':
                        $this->render_crm_tab();
                        break;
                    default:
                        $this->render_analytics_tab();
                }
                ?>
            </div>
        </div>
        <?php
    }
    
    private function render_analytics_tab() {
        ?>
        <div class="irandargah-analytics">
            <div class="irandargah-filters-card">
                <h3><?php esc_html_e('فیلترها', 'irandargah'); ?></h3>
                <div class="irandargah-filters-row">
                    <div class="irandargah-filter-group">
                        <label><?php esc_html_e('بازه زمانی:', 'irandargah'); ?></label>
                        <select id="time-range" class="irandargah-select">
                            <option value="today"><?php esc_html_e('امروز', 'irandargah'); ?></option>
                            <option value="week"><?php esc_html_e('هفته جاری', 'irandargah'); ?></option>
                            <option value="month" selected><?php esc_html_e('ماه جاری', 'irandargah'); ?></option>
                            <option value="year"><?php esc_html_e('سال جاری', 'irandargah'); ?></option>
                            <option value="custom"><?php esc_html_e('سفارشی', 'irandargah'); ?></option>
                        </select>
                    </div>
                    <div class="irandargah-filter-group" id="custom-date-range" style="display: none;">
                        <label><?php esc_html_e('از تاریخ:', 'irandargah'); ?></label>
                        <input type="text" id="date-from" class="irandargah-datepicker" />
                        <label><?php esc_html_e('تا تاریخ:', 'irandargah'); ?></label>
                        <input type="text" id="date-to" class="irandargah-datepicker" />
                    </div>
                    <div class="irandargah-filter-group">
                        <label><?php esc_html_e('درگاه:', 'irandargah'); ?></label>
                        <select id="gateway-filter" class="irandargah-select">
                            <option value="all"><?php esc_html_e('همه درگاه‌ها', 'irandargah'); ?></option>
                            <?php
                            $gateways = $this->get_available_gateways();
                            foreach ($gateways as $gateway_id => $gateway_name) {
                                echo '<option value="' . esc_attr($gateway_id) . '">' . esc_html($gateway_name) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <div class="irandargah-filter-group">
                        <button type="button" class="irandargah-btn irandargah-btn-primary" id="apply-filters">
                            <?php esc_html_e('اعمال فیلتر', 'irandargah'); ?>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="irandargah-stats-grid">
                <div class="irandargah-stat-card">
                    <div class="irandargah-stat-icon" style="background: #10b981;">
                        <span class="dashicons dashicons-yes-alt"></span>
                    </div>
                    <div class="irandargah-stat-content">
                        <h3 id="total-successful">0</h3>
                        <p><?php esc_html_e('تراکنش‌های موفق', 'irandargah'); ?></p>
                    </div>
                </div>
                <div class="irandargah-stat-card">
                    <div class="irandargah-stat-icon" style="background: #ef4444;">
                        <span class="dashicons dashicons-dismiss"></span>
                    </div>
                    <div class="irandargah-stat-content">
                        <h3 id="total-failed">0</h3>
                        <p><?php esc_html_e('تراکنش‌های ناموفق', 'irandargah'); ?></p>
                    </div>
                </div>
                <div class="irandargah-stat-card">
                    <div class="irandargah-stat-icon" style="background: #f59e0b;">
                        <span class="dashicons dashicons-clock"></span>
                    </div>
                    <div class="irandargah-stat-content">
                        <h3 id="total-pending">0</h3>
                        <p><?php esc_html_e('تراکنش‌های معلق', 'irandargah'); ?></p>
                    </div>
                </div>
                <div class="irandargah-stat-card">
                    <div class="irandargah-stat-icon" style="background: #3b82f6;">
                        <span class="dashicons dashicons-money-alt"></span>
                    </div>
                    <div class="irandargah-stat-content">
                        <h3 id="total-revenue">0</h3>
                        <p><?php esc_html_e('درآمد کل', 'irandargah'); ?></p>
                    </div>
                </div>
            </div>
            
            <div class="irandargah-charts-grid">
                <div class="irandargah-chart-card">
                    <h3><?php esc_html_e('روند تراکنش‌ها', 'irandargah'); ?></h3>
                    <canvas id="transactions-trend-chart"></canvas>
                </div>
                <div class="irandargah-chart-card">
                    <h3><?php esc_html_e('سهم درگاه‌ها', 'irandargah'); ?></h3>
                    <canvas id="gateways-share-chart"></canvas>
                </div>
                <div class="irandargah-chart-card">
                    <h3><?php esc_html_e('نرخ موفقیت درگاه‌ها', 'irandargah'); ?></h3>
                    <canvas id="success-rate-chart"></canvas>
                </div>
                <div class="irandargah-chart-card">
                    <h3><?php esc_html_e('درآمد درگاه‌ها', 'irandargah'); ?></h3>
                    <canvas id="revenue-chart"></canvas>
                </div>
            </div>
        </div>
        <?php
    }
    
    private function render_alerts_tab() {
        ?>
        <div class="irandargah-alerts">
            <div class="irandargah-alerts-notification-bar" id="alerts-bar"></div>
            
            <div class="irandargah-alerts-list" id="alerts-list">
                <div class="irandargah-alert-item irandargah-alert-error">
                    <span class="dashicons dashicons-warning"></span>
                    <div class="irandargah-alert-content">
                        <h4><?php esc_html_e('اختلال در درگاه زرین‌پال', 'irandargah'); ?></h4>
                        <p><?php esc_html_e('درگاه زرین‌پال در حال حاضر پاسخ نمی‌دهد. لطفا بررسی کنید.', 'irandargah'); ?></p>
                        <span class="irandargah-alert-time"><?php echo esc_html(current_time('Y/m/d H:i')); ?></span>
                    </div>
                    <button class="irandargah-alert-dismiss">×</button>
                </div>
            </div>
        </div>
        <?php
    }
    
    private function render_transactions_tab() {
        ?>
        <div class="irandargah-transactions">
            <div class="irandargah-transactions-filters">
                <input type="text" id="transaction-search" class="irandargah-search" 
                       placeholder="<?php esc_attr_e('جستجو بر اساس نام، شماره تراکنش یا تاریخ...', 'irandargah'); ?>" />
                <select id="transaction-status-filter" class="irandargah-select">
                    <option value="all"><?php esc_html_e('همه وضعیت‌ها', 'irandargah'); ?></option>
                    <option value="success"><?php esc_html_e('موفق', 'irandargah'); ?></option>
                    <option value="failed"><?php esc_html_e('ناموفق', 'irandargah'); ?></option>
                    <option value="pending"><?php esc_html_e('معلق', 'irandargah'); ?></option>
                </select>
                <button type="button" class="irandargah-btn irandargah-btn-secondary" id="export-transactions">
                    <?php esc_html_e('خروجی CSV', 'irandargah'); ?>
                </button>
            </div>
            
            <div class="irandargah-transactions-table-wrapper">
                <table class="irandargah-transactions-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('ID تراکنش', 'irandargah'); ?></th>
                            <th><?php esc_html_e('نام کاربر', 'irandargah'); ?></th>
                            <th><?php esc_html_e('مبلغ', 'irandargah'); ?></th>
                            <th><?php esc_html_e('درگاه', 'irandargah'); ?></th>
                            <th><?php esc_html_e('وضعیت', 'irandargah'); ?></th>
                            <th><?php esc_html_e('زمان', 'irandargah'); ?></th>
                            <th><?php esc_html_e('عملیات', 'irandargah'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="transactions-tbody">
                        <tr>
                            <td colspan="7" class="irandargah-loading">
                                <?php esc_html_e('در حال بارگذاری...', 'irandargah'); ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <?php
    }
    
    private function render_pending_tab() {
        ?>
        <div class="irandargah-pending">
            <div class="irandargah-pending-filters">
                <select id="pending-age-filter" class="irandargah-select">
                    <option value="all"><?php esc_html_e('همه', 'irandargah'); ?></option>
                    <option value="5"><?php esc_html_e('کمتر از 5 دقیقه', 'irandargah'); ?></option>
                    <option value="15"><?php esc_html_e('کمتر از 15 دقیقه', 'irandargah'); ?></option>
                    <option value="30"><?php esc_html_e('کمتر از 30 دقیقه', 'irandargah'); ?></option>
                    <option value="60"><?php esc_html_e('بیشتر از 1 ساعت', 'irandargah'); ?></option>
                </select>
            </div>
            
            <div class="irandargah-pending-list" id="pending-list">
                <!-- Pending payments will be loaded here -->
            </div>
        </div>
        <?php
    }
    
    private function render_fraud_tab() {
        ?>
        <div class="irandargah-fraud">
            <div class="irandargah-fraud-summary">
                <div class="irandargah-fraud-card">
                    <h3><?php esc_html_e('تراکنش‌های پرریسک امروز', 'irandargah'); ?></h3>
                    <p class="irandargah-fraud-count" id="high-risk-count">0</p>
                </div>
                <div class="irandargah-fraud-card">
                    <h3><?php esc_html_e('بیشترین IP مشکوک', 'irandargah'); ?></h3>
                    <p class="irandargah-fraud-ip" id="suspicious-ip">-</p>
                </div>
            </div>
            
            <div class="irandargah-fraud-list" id="fraud-list">
                <!-- Fraud transactions will be loaded here -->
            </div>
        </div>
        <?php
    }
    
    private function render_crm_tab() {
        ?>
        <div class="irandargah-crm">
            <div class="irandargah-crm-settings">
                <h3><?php esc_html_e('تنظیمات یکپارچگی CRM', 'irandargah'); ?></h3>
                <form id="crm-settings-form">
                    <div class="irandargah-form-group">
                        <label><?php esc_html_e('فعال‌سازی ارسال به CRM', 'irandargah'); ?></label>
                        <input type="checkbox" id="crm-enabled" />
                    </div>
                    <div class="irandargah-form-group">
                        <label><?php esc_html_e('API Endpoint', 'irandargah'); ?></label>
                        <input type="text" id="crm-endpoint" class="irandargah-input" />
                    </div>
                    <div class="irandargah-form-group">
                        <label><?php esc_html_e('API Key', 'irandargah'); ?></label>
                        <input type="password" id="crm-api-key" class="irandargah-input" />
                    </div>
                    <button type="submit" class="irandargah-btn irandargah-btn-primary">
                        <?php esc_html_e('ذخیره تنظیمات', 'irandargah'); ?>
                    </button>
                </form>
            </div>
            
            <div class="irandargah-crm-reports">
                <h3><?php esc_html_e('گزارش‌های دوره‌ای', 'irandargah'); ?></h3>
                <div class="irandargah-form-group">
                    <label><?php esc_html_e('بازه ارسال گزارش', 'irandargah'); ?></label>
                    <select id="report-frequency" class="irandargah-select">
                        <option value="daily"><?php esc_html_e('روزانه', 'irandargah'); ?></option>
                        <option value="weekly"><?php esc_html_e('هفتگی', 'irandargah'); ?></option>
                        <option value="monthly"><?php esc_html_e('ماهانه', 'irandargah'); ?></option>
                    </select>
                </div>
                <button type="button" class="irandargah-btn irandargah-btn-secondary" id="send-test-report">
                    <?php esc_html_e('ارسال گزارش تست', 'irandargah'); ?>
                </button>
            </div>
        </div>
        <?php
    }
    
    private function get_available_gateways() {
        $gateways = [];
        
        // استفاده از IranDargah_Settings_Loader برای دریافت همه درگاه‌ها با نام فارسی
        if (class_exists('IranDargah_Settings_Loader')) {
            $all_gateways = IranDargah_Settings_Loader::get_all_gateways_data();
            foreach ($all_gateways as $gateway) {
                if (isset($gateway['id']) && isset($gateway['title'])) {
                    $gateways[$gateway['id']] = $gateway['title'];
                }
            }
        }
        
        // Fallback: اگر IranDargah_Settings_Loader در دسترس نبود، از WooCommerce استفاده کن
        if (empty($gateways) && class_exists('WC_Payment_Gateways') && function_exists('WC')) {
            $wc_gateways = WC()->payment_gateways->payment_gateways();
            foreach ($wc_gateways as $gateway) {
                if (in_array($gateway->id, irandargah_get_gateway_ids())) {
                    $gateways[$gateway->id] = $gateway->get_title();
                }
            }
        }
        
        return $gateways;
    }
    
    public function ajax_get_reports_data() {
        check_ajax_referer('irandargah_reports_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('دسترسی لازم را ندارید.', 'irandargah')]);
        }
        
        // TODO: Implement actual data fetching from orders/transactions
        $data = [
            'stats' => [
                'successful' => 0,
                'failed' => 0,
                'pending' => 0,
                'revenue' => 0,
            ],
            'charts' => [
                'trend' => [],
                'gateways_share' => [],
                'success_rate' => [],
                'revenue' => [],
            ]
        ];
        
        wp_send_json_success($data);
    }
    
    public function ajax_get_transactions() {
        check_ajax_referer('irandargah_reports_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('دسترسی لازم را ندارید.', 'irandargah')]);
        }
        
        // TODO: Implement actual transaction fetching
        wp_send_json_success(['transactions' => []]);
    }
    
    public function ajax_get_pending_payments() {
        check_ajax_referer('irandargah_reports_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('دسترسی لازم را ندارید.', 'irandargah')]);
        }
        
        // TODO: Implement actual pending payments fetching
        wp_send_json_success(['payments' => []]);
    }
    
    public function ajax_get_fraud_detection() {
        check_ajax_referer('irandargah_reports_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('دسترسی لازم را ندارید.', 'irandargah')]);
        }
        
        // TODO: Implement actual fraud detection
        wp_send_json_success(['fraud' => []]);
    }
}

IranDargah_Reports_Dashboard::get_instance();

