<?php

namespace Unlockafe_Addons\Classes;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

class Reporting_Dashboard_Controller
{
    public function __construct()
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_ajax_unlockafe_get_chart_data', [$this, 'get_chart_data_ajax']);
        add_action('wp_ajax_unlockafe_export_report', [$this, 'export_report']);
    }

    public function enqueue_scripts($hook)
    {
        // The hook for a submenu page is formatted as: {parent_slug}_page_{submenu_slug}
        if ('advanced-coupons_page_unlockafe-coupons-reporting' !== $hook) {
            return;
        }

        wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', [], null, true);
        wp_enqueue_script('unlockafe-reporting-dashboard', UNLOCKAFE_ASSETS . 'js/reporting-dashboard.js', ['jquery', 'chart-js'], UNLOCKAFE_VERSION, true);
        wp_enqueue_style('unlockafe-reporting-dashboard-style', UNLOCKAFE_ASSETS . 'css/reporting-dashboard.css', [], UNLOCKAFE_VERSION);

        $chart_data = $this->get_chart_data();

        wp_localize_script('unlockafe-reporting-dashboard', 'unlockafeReportingData', [
            'usage_trends' => [
                'labels' => array_keys($chart_data),
                'data'   => array_column($chart_data, 'count'),
            ],
            'discounts_over_time' => [
                'labels' => array_keys($chart_data),
                'data'   => array_column($chart_data, 'amount'),
            ],
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('unlockafe_reporting_nonce'),
        ]);
    }

    private function get_chart_data($start_date = null, $end_date = null, $days = 30)
    {
        global $wpdb;
        
        if (!$start_date) {
            $start_date = date('Y-m-d', strtotime("-{$days} days"));
        }
        if (!$end_date) {
            $end_date = date('Y-m-d');
        }

        // Debug: Log the date range
        error_log("UNLOCKAFE DEBUG: Fetching chart data from {$start_date} to {$end_date}");

        try {
            // First, let's check if we have any coupon data at all
            $coupon_check = $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_type = 'coupon'"
            );
            error_log("UNLOCKAFE DEBUG: Total coupon items in database: " . $coupon_check);

            // Check orders in date range
            $order_check = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}posts 
                    WHERE post_type = 'shop_order' 
                    AND post_status IN ('wc-completed', 'wc-processing', 'wc-on-hold')
                    AND DATE(post_date) BETWEEN %s AND %s",
                    $start_date,
                    $end_date
                )
            );
            error_log("UNLOCKAFE DEBUG: Orders in date range: " . $order_check);
        
            // If no orders found, let's check what orders exist and their dates
            if ($order_check == 0) {
                // Check all post types to see what exists
                $all_posts = $wpdb->get_results(
                    "SELECT post_type, COUNT(*) as count FROM {$wpdb->prefix}posts 
                    GROUP BY post_type ORDER BY count DESC"
                );
                error_log("UNLOCKAFE DEBUG: All post types: " . print_r($all_posts, true));
                
                // Check for any WooCommerce orders with different post types
                $wc_orders = $wpdb->get_results(
                    "SELECT ID, post_date, post_status, post_type FROM {$wpdb->prefix}posts 
                    WHERE post_type LIKE '%order%' OR post_type = 'shop_order'
                    ORDER BY post_date DESC LIMIT 10"
                );
                error_log("UNLOCKAFE DEBUG: WooCommerce orders: " . print_r($wc_orders, true));
                
                // Check if using HPOS (High Performance Order Storage)
                $hpos_orders = $wpdb->get_results(
                    "SELECT id, date_created_gmt, status FROM {$wpdb->prefix}wc_orders 
                    ORDER BY date_created_gmt DESC LIMIT 10"
                );
                error_log("UNLOCKAFE DEBUG: HPOS orders: " . print_r($hpos_orders, true));
            }

            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT DATE(p.post_date) as date, COUNT(oi.order_item_id) as count, SUM(CAST(oim.meta_value AS DECIMAL(10,2))) as amount
                    FROM {$wpdb->prefix}posts as p
                    INNER JOIN {$wpdb->prefix}woocommerce_order_items as oi ON p.ID = oi.order_id
                    INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta as oim ON oi.order_item_id = oim.order_item_id
                    WHERE p.post_type = 'shop_order'
                    AND p.post_status IN ('wc-completed', 'wc-processing', 'wc-on-hold')
                    AND oi.order_item_type = 'coupon'
                    AND oim.meta_key = 'discount_amount'
                    AND DATE(p.post_date) BETWEEN %s AND %s
                    GROUP BY DATE(p.post_date)
                    ORDER BY DATE(p.post_date) ASC",
                    $start_date,
                    $end_date
                )
            );

            error_log("UNLOCKAFE DEBUG: Chart query returned " . count($results) . " rows");
            if (!empty($results)) {
                error_log("UNLOCKAFE DEBUG: Sample result: " . print_r($results[0], true));
            }

        } catch (\Exception $e) {
            error_log('UNLOCKAFE: Chart data query error: ' . $e->getMessage());
            $results = [];
        }

        // Initialize data array with all dates in range
        $data = [];
        $current_date = strtotime($start_date);
        $end_timestamp = strtotime($end_date);
        
        while ($current_date <= $end_timestamp) {
            $date_key = date('Y-m-d', $current_date);
            $data[$date_key] = ['count' => 0, 'amount' => 0];
            $current_date = strtotime('+1 day', $current_date);
        }

        // Fill in actual data
        if (!empty($results)) {
            foreach ($results as $row) {
                $data[$row->date] = [
                    'count' => (int)$row->count, 
                    'amount' => (float)$row->amount
                ];
            }
        }

        return $data;
    }

    private function get_top_coupons($limit = 10, $start_date = null, $end_date = null)
    {
        global $wpdb;
        
        $date_condition = '';
        $params = [];
        
        if ($start_date && $end_date) {
            $date_condition = 'AND DATE(p.post_date) BETWEEN %s AND %s';
            $params = [$start_date, $end_date, $limit];
        } else {
            $params = [$limit];
        }
        
        try {
            return $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT oi.order_item_name as coupon_code, 
                           COUNT(oi.order_item_id) as usage_count, 
                           SUM(CAST(oim.meta_value AS DECIMAL(10,2))) as total_discount,
                           AVG(CAST(oim.meta_value AS DECIMAL(10,2))) as avg_discount
                    FROM {$wpdb->prefix}woocommerce_order_items as oi
                    INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta as oim ON oi.order_item_id = oim.order_item_id
                    " . ($start_date ? "INNER JOIN {$wpdb->prefix}posts as p ON oi.order_id = p.ID" : "") . "
                    WHERE oi.order_item_type = 'coupon'
                    AND oim.meta_key = 'discount_amount'
                    " . $date_condition . "
                    GROUP BY oi.order_item_name
                    ORDER BY usage_count DESC
                    LIMIT %d",
                    ...$params
                )
            );
        } catch (\Exception $e) {
            error_log('UNLOCKAFE: Top coupons query error: ' . $e->getMessage());
            return [];
        }
    }

    public function get_chart_data_ajax()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'unlockafe_reporting_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }

        $start_date = sanitize_text_field($_POST['start_date'] ?? '');
        $end_date = sanitize_text_field($_POST['end_date'] ?? '');
        
        try {
            $chart_data = $this->get_chart_data($start_date, $end_date);
            $top_coupons = $this->get_top_coupons(10, $start_date, $end_date);
        } catch (Exception $e) {
            wp_send_json_error('Failed to fetch data: ' . $e->getMessage());
            return;
        }
        
        $labels = array_keys($chart_data);
        $usage_data = array_column($chart_data, 'count');
        $discount_data = array_column($chart_data, 'amount');
        
        // Calculate summary statistics
        $total_coupons = array_sum($usage_data);
        $total_discount = array_sum($discount_data);
        $avg_discount = $total_coupons > 0 ? $total_discount / $total_coupons : 0;
        $most_used_coupon = !empty($top_coupons) ? $top_coupons[0]->coupon_code : 'N/A';
        
        // Debug logging
        error_log("UNLOCKAFE DEBUG: Summary calculations - Total Coupons: {$total_coupons}, Total Discount: {$total_discount}, Avg Discount: {$avg_discount}, Most Used: {$most_used_coupon}");
        error_log("UNLOCKAFE DEBUG: Usage data: " . print_r($usage_data, true));
        error_log("UNLOCKAFE DEBUG: Discount data: " . print_r($discount_data, true));
        error_log("UNLOCKAFE DEBUG: Top coupons: " . print_r($top_coupons, true));
        
        wp_send_json_success([
            'usage_trends' => [
                'labels' => $labels,
                'data' => $usage_data
            ],
            'discounts_over_time' => [
                'labels' => $labels,
                'data' => $discount_data
            ],
            'summary' => [
                'total_coupons' => $total_coupons,
                'total_discount' => '$' . number_format($total_discount, 2),
                'average_discount' => '$' . number_format($avg_discount, 2),
                'most_used_coupon' => $most_used_coupon
            ],
            'top_coupons' => $top_coupons
        ]);
    }

    public function export_report()
    {
        if (!wp_verify_nonce($_POST['nonce'], 'unlockafe_reporting_nonce')) {
            wp_die('Security check failed');
        }

        $start_date = sanitize_text_field($_POST['start_date'] ?? '');
        $end_date = sanitize_text_field($_POST['end_date'] ?? '');
        $format = sanitize_text_field($_POST['format'] ?? 'csv');
        
        $chart_data = $this->get_chart_data($start_date, $end_date);
        $top_coupons = $this->get_top_coupons(50, $start_date, $end_date);
        
        if ($format === 'csv') {
            $this->export_csv($chart_data, $top_coupons, $start_date, $end_date);
        }
    }

    private function export_csv($chart_data, $top_coupons, $start_date, $end_date)
    {
        $filename = 'coupon-report-' . $start_date . '-to-' . $end_date . '.csv';
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        
        // Chart data section
        fputcsv($output, ['Coupon Usage Report - ' . $start_date . ' to ' . $end_date]);
        fputcsv($output, []);
        fputcsv($output, ['Date', 'Usage Count', 'Total Discount Amount']);
        
        foreach ($chart_data as $date => $data) {
            fputcsv($output, [$date, $data['count'], $data['amount']]);
        }
        
        // Top coupons section
        fputcsv($output, []);
        fputcsv($output, ['Top Performing Coupons']);
        fputcsv($output, ['Coupon Code', 'Usage Count', 'Total Discount', 'Average Discount']);
        
        foreach ($top_coupons as $coupon) {
            fputcsv($output, [
                $coupon->coupon_code,
                $coupon->usage_count,
                $coupon->total_discount,
                $coupon->avg_discount
            ]);
        }
        
        fclose($output);
        exit;
    }


    public function render_reporting_page()
    {
        $top_coupons = $this->get_top_coupons();
        ?>
        <div class="wrap unlockafe-reporting-dashboard">
            <h1><?php echo esc_html__('Coupons Reporting Dashboard', 'unlock-addons-for-elementor'); ?></h1>
            
            <!-- Date Range Controls -->
            <div class="date-controls">
                <div class="date-range-picker">
                    <label for="start-date"><?php _e('Start Date:', 'unlock-addons-for-elementor'); ?></label>
                    <input type="date" id="start-date" value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>">
                    
                    <label for="end-date"><?php _e('End Date:', 'unlock-addons-for-elementor'); ?></label>
                    <input type="date" id="end-date" value="<?php echo date('Y-m-d'); ?>">
                    
                    <button type="button" id="update-charts" class="button button-primary">
                        <?php _e('Update Charts', 'unlock-addons-for-elementor'); ?>
                    </button>
                    
                    <button type="button" id="export-report" class="button button-secondary">
                    <?php _e('Export CSV', 'unlock-addons-for-elementor'); ?>
                </button>
                </div>
                
                <div class="quick-filters">
                    <button type="button" class="button quick-filter" data-days="7"><?php _e('Last 7 Days', 'unlock-addons-for-elementor'); ?></button>
                    <button type="button" class="button quick-filter" data-days="30"><?php _e('Last 30 Days', 'unlock-addons-for-elementor'); ?></button>
                    <button type="button" class="button quick-filter" data-days="90"><?php _e('Last 90 Days', 'unlock-addons-for-elementor'); ?></button>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="summary-cards">
                <div class="summary-card">
                    <h3><?php _e('Total Coupons Used', 'unlock-addons-for-elementor'); ?></h3>
                    <span class="summary-value" id="total-usage">-</span>
                </div>
                <div class="summary-card">
                    <h3><?php _e('Total Discount Given', 'unlock-addons-for-elementor'); ?></h3>
                    <span class="summary-value" id="total-discount">-</span>
                </div>
                <div class="summary-card">
                    <h3><?php _e('Average Discount', 'unlock-addons-for-elementor'); ?></h3>
                    <span class="summary-value" id="avg-discount">-</span>
                </div>
                <div class="summary-card">
                    <h3><?php _e('Most Used Coupon', 'unlock-addons-for-elementor'); ?></h3>
                    <span class="summary-value" id="top-coupon">-</span>
                </div>
            </div>
            
            <!-- Charts -->
            <div class="charts-wrapper">
                <div class="chart-container">
                    <h3><?php _e('Usage Trends', 'unlock-addons-for-elementor'); ?></h3>
                    <div class="chart-loading" id="usage-loading" style="display: none;">
                        <?php _e('Loading...', 'unlock-addons-for-elementor'); ?>
                    </div>
                    <canvas id="unlockafeUsageTrendsChart"></canvas>
                </div>
                <div class="chart-container">
                    <h3><?php _e('Discounts Given', 'unlock-addons-for-elementor'); ?></h3>
                    <div class="chart-loading" id="discount-loading" style="display: none;">
                        <?php _e('Loading...', 'unlock-addons-for-elementor'); ?>
                    </div>
                    <canvas id="unlockafeDiscountsOverTimeChart"></canvas>
                </div>
            </div>

            <!-- Top Coupons Table -->
            <div class="top-coupons-container">
                <h2><?php _e('Top Performing Coupons', 'unlock-addons-for-elementor'); ?></h2>
                <div class="table-loading" id="table-loading" style="display: none;">
                    <?php _e('Loading...', 'unlock-addons-for-elementor'); ?>
                </div>
                <div id="top-coupons-table">
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php _e('Coupon Code', 'unlock-addons-for-elementor'); ?></th>
                                <th><?php _e('Usage Count', 'unlock-addons-for-elementor'); ?></th>
                                <th><?php _e('Total Discount', 'unlock-addons-for-elementor'); ?></th>
                                <th><?php _e('Average Discount', 'unlock-addons-for-elementor'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($top_coupons)) : ?>
                                <?php foreach ($top_coupons as $coupon) : ?>
                                    <tr>
                                        <td><strong><?php echo esc_html($coupon->coupon_code); ?></strong></td>
                                        <td><?php echo esc_html($coupon->usage_count); ?></td>
                                        <td><?php echo wc_price($coupon->total_discount); ?></td>
                                        <td><?php echo wc_price($coupon->avg_discount ?? 0); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else : ?>
                                <tr>
                                    <td colspan="4"><?php _e('No coupon data found.', 'unlock-addons-for-elementor'); ?></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php
    }
}
