<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Reports Tab - Standardized with afdp_ prefixes and Dynamic Currency
 */
function afdp_reports_tab() {
    // 1. GET DYNAMIC CURRENCY (Synced with Payments Tab)
    $afdp_currency_code = get_option('afdp_currency', 'USD');
    $afdp_symbols = [
        'USD' => '$', 'GBP' => '£', 'EUR' => '€', 'INR' => '₹', 'BDT' => '৳',
        'AUD' => 'A$', 'CAD' => 'C$', 'JPY' => '¥', 'AED' => 'د.إ', 'SAR' => 'SR'
    ];
    $afdp_symbol = isset($afdp_symbols[$afdp_currency_code]) ? $afdp_symbols[$afdp_currency_code] : $afdp_currency_code;

    // 2. SECURE INPUTS
    $afdp_filter_status = isset($_GET['afdp_status']) ? sanitize_text_field(wp_unslash($_GET['afdp_status'])) : '';
    $afdp_filter_from   = isset($_GET['afdp_from']) ? sanitize_text_field(wp_unslash($_GET['afdp_from'])) : '';
    $afdp_filter_to     = isset($_GET['afdp_to']) ? sanitize_text_field(wp_unslash($_GET['afdp_to'])) : '';

    // 3. PERFORMANCE QUERY
    $args = [
        'post_type'   => 'afdp_food_order', // Standardized Post Type
        'numberposts' => -1,
        'orderby'     => 'date',
        'order'       => 'DESC',
    ];

    if ($afdp_filter_status) {
        $args['meta_query'][] = [
            'key'   => 'afdp_order_status', 
            'value' => $afdp_filter_status
        ];
    }
    
    if ($afdp_filter_from || $afdp_filter_to) {
        $args['date_query'] = [['inclusive' => true]];
        if ($afdp_filter_from) $args['date_query'][0]['after'] = $afdp_filter_from;
        if ($afdp_filter_to)   $args['date_query'][0]['before'] = $afdp_filter_to;
    }

    $afdp_filtered_orders = get_posts($args);

    // 4. LOGIC
    $afdp_total_revenue = 0;
    $afdp_completed = 0;
    $afdp_pending = 0;

    foreach ($afdp_filtered_orders as $afdp_o) {
        $afdp_price = floatval(get_post_meta($afdp_o->ID, 'afdp_total_price', true));
        $afdp_status = strtolower(get_post_meta($afdp_o->ID, 'afdp_order_status', true) ?: 'pending');
        
        $afdp_total_revenue += $afdp_price;
        if ($afdp_status === 'completed') {
            $afdp_completed++;
        } else {
            $afdp_pending++;
        }
    }
    ?>

    <style>
        .afdp-reports-wrap { padding: 20px; font-family: 'Inter', -apple-system, sans-serif; }
        .afdp-flex-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        
        /* Stats Cards */
        .afdp-stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 30px; }
        .afdp-stat-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid #e2e8f0; position: relative; }
        .afdp-stat-label { display: block; color: #64748b; font-size: 13px; font-weight: 600; margin-bottom: 5px; }
        .afdp-stat-value { display: block; font-size: 24px; font-weight: 800; color: #0f172a; }
        .afdp-stat-icon { position: absolute; right: 20px; top: 20px; color: #e2e8f0; font-size: 30px; }
        
        /* Filter Bar */
        .afdp-filter-bar { 
            background: #fff; padding: 20px; border-radius: 12px; border: 1px solid #e2e8f0; 
            display: flex; gap: 15px; align-items: flex-end; margin-bottom: 30px; 
        }
        .afdp-filter-group { display: flex; flex-direction: column; gap: 5px; }
        .afdp-filter-group label { font-size: 12px; font-weight: 700; color: #475569; }
        .afdp-filter-group select, .afdp-filter-group input { 
            border: 1px solid #e2e8f0; border-radius: 6px; padding: 8px; min-width: 150px;
        }

        /* Status Badges */
        .afdp-badge { 
            display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; 
            border-radius: 20px; font-size: 12px; font-weight: 700; 
        }
        .afdp-badge-completed { background: #ecfdf5; color: #10b981; }
        .afdp-badge-pending { background: #fff7ed; color: #f59e0b; }
        .afdp-badge-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }

        .afdp-btn-export { 
            background: #fff; border: 1px solid #e2e8f0; padding: 8px 16px; 
            border-radius: 8px; font-weight: 700; cursor: pointer; display: flex; align-items: center; gap: 8px;
        }
    </style>

    <div class="afdp-reports-wrap">
        <div class="afdp-flex-header">
            <h1 style="font-weight: 900; margin: 0;">Analytics Overview</h1>
            <button class="afdp-btn-export" onclick="window.print()">
                <span class="dashicons dashicons-download"></span> Export Report
            </button>
        </div>

        <div class="afdp-stats-grid">
            <div class="afdp-stat-card">
                <span class="afdp-stat-icon dashicons dashicons-cart"></span>
                <span class="afdp-stat-label">Total Orders</span>
                <span class="afdp-stat-value"><?php echo count($afdp_filtered_orders); ?></span>
            </div>
            <div class="afdp-stat-card" style="border-left: 4px solid #e53935;">
                <span class="afdp-stat-icon dashicons dashicons-chart-area"></span>
                <span class="afdp-stat-label">Gross Revenue</span>
                <span class="afdp-stat-value"><?php echo esc_attr($afdp_symbol . number_format($afdp_total_revenue, 2)); ?></span>
            </div>
            <div class="afdp-stat-card">
                <span class="afdp-stat-icon dashicons dashicons-yes-alt"></span>
                <span class="afdp-stat-label">Completed</span>
                <span class="afdp-stat-value" style="color:#10b981;"><?php echo esc_html($afdp_completed); ?></span>
            </div>
            <div class="afdp-stat-card">
                <span class="afdp-stat-icon dashicons dashicons-clock"></span>
                <span class="afdp-stat-label">In Progress</span>
                <span class="afdp-stat-value" style="color:#f59e0b;"><?php echo esc_html($afdp_pending); ?></span>
            </div>
        </div>

        <form method="get" class="afdp-filter-bar">
            <input type="hidden" name="page" value="<?php echo esc_attr($_GET['page'] ?? 'afdp_delivery_system'); ?>">
            <input type="hidden" name="tab" value="reports">
            
            <div class="afdp-filter-group">
                <label>Filter Status</label>
                <select name="afdp_status">
                    <option value="">All Statuses</option>
                    <option value="completed" <?php selected($afdp_filter_status,'completed'); ?>>Completed</option>
                    <option value="pending" <?php selected($afdp_filter_status,'pending'); ?>>Pending</option>
                </select>
            </div>

            <div class="afdp-filter-group">
                <label>From Date</label>
                <input type="date" name="afdp_from" value="<?php echo esc_attr($afdp_filter_from); ?>">
            </div>

            <div class="afdp-filter-group">
                <label>To Date</label>
                <input type="date" name="afdp_to" value="<?php echo esc_attr($afdp_filter_to); ?>">
            </div>

            <button type="submit" class="button button-primary" style="background:#e53935; border:none; height:38px; padding: 0 25px; font-weight:700;">
                Filter Results
            </button>
            <a href="?page=afdp_delivery_system&tab=reports" style="text-decoration:none; font-size:12px; color:#64748b; margin-bottom:10px;">Reset</a>
        </form>

        <div style="background:#fff; border: 1px solid #e2e8f0; border-radius:12px; overflow:hidden;">
            <table class="widefat fixed striped">
                <thead>
                    <tr>
                        <th style="padding:15px; font-weight:700;">Order ID</th>
                        <th style="padding:15px; font-weight:700;">Customer</th>
                        <th style="padding:15px; font-weight:700;">Revenue</th>
                        <th style="padding:15px; font-weight:700;">Status</th>
                        <th style="padding:15px; font-weight:700;">Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($afdp_filtered_orders) : foreach($afdp_filtered_orders as $afdp_o):
                        $afdp_cust = get_post_meta($afdp_o->ID, 'afdp_customer_name', true) ?: 'Guest';
                        $afdp_rev  = floatval(get_post_meta($afdp_o->ID, 'afdp_total_price', true));
                        $afdp_st   = strtolower(get_post_meta($afdp_o->ID, 'afdp_order_status', true) ?: 'pending');
                    ?>
                    <tr>
                        <td style="padding:15px;">#<?php echo esc_attr($afdp_o->ID); ?></td>
                        <td style="padding:15px; font-weight:600;"><?php echo esc_html($afdp_cust); ?></td>
                        <td style="padding:15px; color:#e53935; font-weight:700;">
                            <?php echo esc_attr($afdp_symbol . number_format($afdp_rev, 2)); ?>
                        </td>
                        <td style="padding:15px;">
                            <div class="afdp-badge afdp-badge-<?php echo esc_attr($afdp_st); ?>">
                                <span class="afdp-badge-dot"></span> <?php echo esc_attr(ucfirst($afdp_st)); ?>
                            </div>
                        </td>
                        <td style="padding:15px; color:#64748b;"><?php echo get_the_date('M j, Y • H:i', $afdp_o->ID); ?></td>
                    </tr>
                    <?php endforeach; else : ?>
                        <tr><td colspan="5" style="padding:30px; text-align:center; color:#64748b;">No matching orders found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php
}