<?php
// Transactions admin page template for Elementor Pay Addons
use Elementor_Pay_Addons\Shared\Logger;
use Elementor_Pay_Addons\Shared\Utils;
use Elementor_Pay_Addons\Stripe\Stripe_Helper;
use Elementor_Pay_Addons\Database\Transaction_Query;

if (!defined('ABSPATH')) exit;

if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'pay-addons-for-elementor' ) );
}

$order_by = isset($_GET['order_by']) ? sanitize_text_field( wp_unslash( $_GET['order_by'] ) ) : 'created_at'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$order_dir = isset($_GET['order_dir']) && strtolower( sanitize_text_field( wp_unslash( $_GET['order_dir'] ) ) ) === 'asc' ? 'ASC' : 'DESC'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$args = [
    'search'   => isset($_GET['search']) ? sanitize_text_field( wp_unslash( $_GET['search'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    'status'   => isset($_GET['status']) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    'page'     => isset($_GET['paged']) ? max(1, absint( $_GET['paged'] )) : 1, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    'date_start' => isset($_GET['date_start']) ? sanitize_text_field( wp_unslash( $_GET['date_start'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    'date_end' => isset($_GET['date_end']) ? sanitize_text_field( wp_unslash( $_GET['date_end'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    'per_page' => 10,
    'order_by' => $order_by,
    'order_dir' => $order_dir,
];
$result = Transaction_Query::get_instance()->get_transactions($args);
$transactions = $result['data'];
$total = $result['total'];
$paged = $result['page'];
$per_page = $result['per_page'];
$summary = Transaction_Query::get_instance()->get_summary($args);
$total_revenue = $summary['total_revenue'] ?? 0;
$total_transactions_all = $summary['total_transactions'] ?? 0;
$status_counts = $summary['status_counts'] ?? [];
// Build chart data from transactions (no SQL grouping) - fetch all matching transactions
$chart_args = $args;
$chart_args['no_limit'] = true;
$chart_args['page'] = 1;
$chart_result = Transaction_Query::get_instance()->get_transactions($chart_args);
$chart_transactions = $chart_result['data'] ?? [];

// Determine date range: explicit date_start/date_end prefered, otherwise derive from data, otherwise fallback to last 30 days
if (!empty($args['date_start']) || !empty($args['date_end'])) {
    $start_date = !empty($args['date_start']) ? gmdate('Y-m-d', strtotime($args['date_start'])) : gmdate('Y-m-d');
    $end_date = !empty($args['date_end']) ? gmdate('Y-m-d', strtotime($args['date_end'])) : gmdate('Y-m-d');
    if (strtotime($start_date) > strtotime($end_date)) {
        $tmp = $start_date; $start_date = $end_date; $end_date = $tmp;
    }
} elseif (!empty($chart_transactions)) {
    $dates = array_map(function($t) { return gmdate('Y-m-d', strtotime($t['created_at'])); }, $chart_transactions);
    $start_date = min($dates);
    $end_date = max($dates);
} else {
    $days = 30;
    $end_date = gmdate('Y-m-d');
    $start_date = gmdate('Y-m-d', strtotime("-" . ($days - 1) . " days"));
}

// Initialize per-day buckets
$revenue_by_day_map = [];
$period_days = (int) ( ( strtotime($end_date) - strtotime($start_date) ) / DAY_IN_SECONDS ) + 1;
for ($i = 0; $i < $period_days; $i++) {
    $d = gmdate('Y-m-d', strtotime("+{$i} days", strtotime($start_date)));
    $revenue_by_day_map[$d] = [
        'success' => 0.0,
        'failed' => 0.0,
        'pending' => 0.0,
    ];
}

// Accumulate amounts from fetched transactions
foreach (($chart_transactions ?: []) as $t) {
    $day = gmdate('Y-m-d', strtotime($t['created_at']));
    if (!isset($revenue_by_day_map[$day])) continue; // ignore out-of-range rows
    $raw_status = isset($t['payment_status']) ? strtolower(trim($t['payment_status'])) : '';
    $amount = floatval($t['amount']) - (floatval($t['refund_amount'] ?? 0));
    if (in_array($raw_status, ['success', 'succeeded', 'paid', 'completed', 'ok', 'confirmed'])) {
        $revenue_by_day_map[$day]['success'] += $amount;
    } elseif (in_array($raw_status, ['failed', 'failure', 'declined', 'cancelled', 'canceled', 'charge_failed'])) {
        $revenue_by_day_map[$day]['failed'] += $amount;
    } elseif (in_array($raw_status, ['pending', 'requires_payment', 'incomplete', 'pending_payment', 'processing'])) {
        $revenue_by_day_map[$day]['pending'] += $amount;
    }
}

// Convert to array-of-objects format expected by frontend
$revenue_by_day = array_map(function($k, $v) {
    return ['day' => $k, 'success' => $v['success'], 'failed' => $v['failed'], 'pending' => $v['pending']];
}, array_keys($revenue_by_day_map), $revenue_by_day_map);

// Determine chart currency from available transactions
$chart_currency = 'USD';
if (!empty($chart_transactions) && isset($chart_transactions[0]['currency'])) {
    $chart_currency = strtoupper($chart_transactions[0]['currency']);
} elseif (!empty($transactions) && isset($transactions[0]['currency'])) {
    $chart_currency = strtoupper($transactions[0]['currency']);
}

// Revenue totals per status (in cents)
$revenue_by_status = $summary['revenue_by_status'] ?? [];
$failed_rev = $revenue_by_status['failed'] ?? 0;
$success_rev = $revenue_by_status['success'] ?? 0;
$pending_rev = $revenue_by_status['pending'] ?? 0;
$display_currency = $chart_currency;
?>

<!-- --- Professionally Styled & Fixed Page --- -->
<div id="transactions" class="bg-slate-50 p-4 sm:p-6 lg:p-8 min-h-screen">

  <h2 class="text-3xl font-bold text-slate-800 mb-6">Transactions</h2>

  <!-- Page Tabs -->
  <div class="mb-6">
    <div role="tablist" aria-label="Transactions pages" class="inline-flex rounded-lg border border-slate-200 bg-white p-1 shadow-sm">
      <button id="epa-tab-report" role="tab" aria-selected="true" data-tab="report" class="px-4 py-2 rounded-md font-semibold text-sm text-slate-600 focus:outline-none focus:ring-2 focus:ring-indigo-400">Overview</button>
      <button id="epa-tab-transactions" role="tab" aria-selected="false" data-tab="transactions" class="px-4 py-2 rounded-md font-semibold text-sm text-slate-600 focus:outline-none focus:ring-2 focus:ring-indigo-400">Transactions</button>
    </div>
  </div>

  <!-- Report Panel -->
  <div id="epa-panel-report" role="tabpanel" aria-labelledby="epa-tab-report">
    <!-- Date Range Filter -->
    <div class="bg-white p-4 rounded-xl border border-slate-200 shadow-sm mb-6">
      <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between">
        <div class="inline-flex flex-wrap items-center gap-2">
          <button type="button" class="epa-range-btn bg-slate-100 hover:bg-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-sm font-medium" data-range="7">Last 7 days</button>
          <button type="button" class="epa-range-btn bg-slate-100 hover:bg-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-sm font-medium" data-range="30">Last 30 days</button>
          <button type="button" class="epa-range-btn bg-slate-100 hover:bg-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-sm font-medium" data-range="this_month">This Month</button>
          <button type="button" class="epa-range-btn bg-slate-100 hover:bg-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-sm font-medium" data-range="last_month">Last Month</button>
          <button type="button" class="epa-range-btn bg-slate-100 hover:bg-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-sm font-medium" data-range="all">All Time</button>
        </div>
        <div class="text-sm text-slate-500 mt-3 sm:mt-0" id="epa-range-label">Showing: <span id="epa-range-value" class="font-semibold">All time</span></div>
      </div>
    </div>
    
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <div class="bg-violet-50 p-6 rounded-2xl border border-violet-100">
        <h4 class="text-sm font-medium text-violet-700">Total Transactions</h4>
        <p class="text-3xl font-bold text-violet-900 mt-2"><?php echo esc_html(number_format_i18n($total_transactions_all)); ?></p>
      </div>
      <div class="bg-green-50 p-6 rounded-2xl border border-green-100">
        <h4 class="text-sm font-medium text-green-700">Success Revenue</h4>
        <p class="text-3xl font-bold text-green-800 mt-2"><?php echo esc_html(Stripe_Helper::format_price(['unit_amount' => $success_rev, 'currency' => $display_currency])); ?></p>
      </div>
      <div class="bg-red-50 p-6 rounded-2xl border border-red-100">
        <h4 class="text-sm font-medium text-red-700">Failed Revenue</h4>
        <p class="text-3xl font-bold text-red-800 mt-2"><?php echo esc_html(Stripe_Helper::format_price(['unit_amount' => $failed_rev, 'currency' => $display_currency])); ?></p>
      </div>
      <div class="bg-amber-50 p-6 rounded-2xl border border-amber-100">
        <h4 class="text-sm font-medium text-amber-700">Pending Revenue</h4>
        <p class="text-3xl font-bold text-amber-800 mt-2"><?php echo esc_html(Stripe_Helper::format_price(['unit_amount' => $pending_rev, 'currency' => $display_currency])); ?></p>
      </div>
    </div>

    <!-- Charts (FIX: Flex layout to prevent legend clipping) -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div class="lg:col-span-2 bg-white p-6 rounded-2xl border border-slate-200 shadow-sm flex flex-col h-96"><h3 class="text-base font-semibold text-slate-700 mb-4 flex-shrink-0">Revenue</h3><div class="relative flex-grow"><canvas id="epa-revenue-chart"></canvas></div></div>
      <div class="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm flex flex-col h-96"><h3 class="text-base font-semibold text-slate-700 mb-4 flex-shrink-0">Status Distribution</h3><div class="relative flex-grow flex items-center justify-center"><canvas id="epa-status-chart" style="max-height: 100%;"></canvas></div></div>
    </div>
  </div>

  <!-- Transactions Panel -->
  <div id="epa-panel-transactions" role="tabpanel" aria-labelledby="epa-tab-transactions" class="hidden">
    <!-- Filters -->
    <div class="bg-white p-4 rounded-xl border border-slate-200 shadow-sm mb-6">
        <form id="epa-transactions-filters" method="get" action="<?php echo esc_url( admin_url('admin.php') ); ?>" class="flex flex-col md:flex-row w-full items-start md:items-center justify-between gap-4">
            <div class="flex flex-wrap items-center gap-2">
                <select name="status" class="border-slate-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm">
                    <option value="">All Statuses</option>
                    <option value="success" <?php if (($_GET['status'] ?? '') === 'success') echo 'selected'; ?>>Success</option>
                    <option value="pending" <?php if (($_GET['status'] ?? '') === 'pending') echo 'selected'; ?>>Pending</option>
                    <option value="failed" <?php if (($_GET['status'] ?? '') === 'failed') echo 'selected'; ?>>Failed</option>
                </select>
                <input type="date" name="date_start" id="epa-date-start" value="<?php echo esc_attr($_GET['date_start'] ?? ''); ?>" class="border-slate-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm w-40" />
                <input type="date" name="date_end" id="epa-date-end" value="<?php echo esc_attr($_GET['date_end'] ?? ''); ?>" class="border-slate-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm w-40" />
            </div>
            <div class="flex w-full md:w-auto items-center gap-2">
                <input type="text" name="search" placeholder="Search..." value="<?php echo esc_attr($_GET['search'] ?? ''); ?>" class="w-full md:w-56 border-slate-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm" />
                <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Filter</button>
                <button type="button" id="epa-reset-filters" class="bg-slate-200 hover:bg-slate-300 text-slate-700 px-4 py-2 rounded-lg font-semibold">Reset</button>
            </div>
            <input type="hidden" name="page" value="elementor-pay-addons-transactions">
            <input type="hidden" name="tab" id="epa-form-tab" value="transactions">
        </form>
    </div>

    <!-- Transactions Table -->
    <div class="overflow-x-auto bg-white rounded-xl border border-slate-200 shadow-sm">
      <table class="min-w-full">
        <thead class="bg-slate-50">
          <tr>
            <th class="p-4 font-semibold text-left text-sm text-slate-600">Form</th>
            <th class="p-4 font-semibold text-center text-sm text-slate-600"><a href="?<?php echo esc_attr( http_build_query(array_merge( array_map( 'sanitize_text_field', wp_unslash( $_GET ) ), ['order_by' => 'payment_status', 'order_dir' => $order_by === 'payment_status' && $order_dir === 'ASC' ? 'desc' : 'asc'])) ); ?>#transactions" class="flex items-center justify-center gap-1.5">Status <?php if($order_by === 'payment_status') echo esc_html( $order_dir === 'ASC' ? '▲' : '▼' ); ?></a></th>
            <th class="p-4 font-semibold text-center text-sm text-slate-600"><a href="?<?php echo esc_attr( http_build_query(array_merge( array_map( 'sanitize_text_field', wp_unslash( $_GET ) ), ['order_by' => 'amount', 'order_dir' => $order_by === 'amount' && $order_dir === 'ASC' ? 'desc' : 'asc'])) ); ?>#transactions" class="flex items-center justify-center gap-1.5">Amount <?php if($order_by === 'amount') echo esc_html( $order_dir === 'ASC' ? '▲' : '▼' ); ?></a></th>
            <th class="p-4 font-semibold text-left text-sm text-slate-600">Customer</th>
            <th class="p-4 font-semibold text-left text-sm text-slate-600">Date</th>
            <th class="p-4 font-semibold text-center text-sm text-slate-600">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-200">
          <?php if (empty($transactions)): ?>
            <tr><td colspan="6" class="p-8 text-center text-slate-500"><div class="flex flex-col items-center justify-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-slate-300" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H4a3 3 0 00-3 3v8a3 3 0 003 3z" /></svg><span class="text-lg font-semibold text-slate-500 mt-2">No Transactions Found</span><span class="text-sm text-slate-400">No records match your filters.</span></div></td></tr>
          <?php else: ?>
            <?php foreach ($transactions as $txn): ?>
              <tr class="hover:bg-slate-50 transition-colors">
                <td class="p-4 text-sm text-slate-700 font-medium"><?php echo esc_html($txn['form_name']); ?></td>
                <td class="p-4 text-center"><span class="px-2.5 py-1 rounded-full text-xs font-semibold <?php if ($txn['payment_status'] === 'success') echo 'bg-green-100 text-green-800'; elseif ($txn['payment_status'] === 'failed') echo 'bg-red-100 text-red-800'; elseif ($txn['payment_status'] === 'pending') echo 'bg-yellow-100 text-yellow-800'; else echo 'bg-slate-100 text-slate-800';?>"><?php echo esc_html(ucfirst($txn['payment_status'])); ?></span></td>
                <td class="p-4 text-center text-sm text-slate-700 font-medium"><?php echo Stripe_Helper::format_price($txn['recurring'] ? ['unit_amount' => $txn['amount'],'currency' => $txn['currency'],'recurring' => ['interval' => $txn['recurring_interval'],'interval_count' => $txn['recurring_count']]] : ['unit_amount' => $txn['amount'],'currency' => $txn['currency']]); ?></td>
                <td class="p-4 text-sm text-slate-700"><div class="font-medium text-slate-800"><?php echo esc_html($txn['customer_name']); ?></div><div class="text-slate-500"><?php echo esc_html($txn['customer_email']); ?></div></td>
                <td class="p-4 text-sm text-slate-500"><?php echo esc_html(date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($txn['created_at']))); ?></td>
                <td class="p-4 text-center"><button type="button" class="epa-view-btn text-indigo-600 hover:text-indigo-800 font-semibold text-sm" data-id="<?php echo esc_attr($txn['id']); ?>">View</button><button type="button" class="epa-delete-btn text-red-500 hover:text-red-700 font-semibold text-sm ml-4" data-id="<?php echo esc_attr($txn['id']); ?>">Delete</button></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    <!-- Pagination -->
    <?php if (ceil($total / $per_page) > 1): ?>
      <div class="mt-6 flex flex-col sm:flex-row items-center justify-between text-sm text-slate-600">
        <span class="mb-2 sm:mb-0">Page <?php echo $paged; ?> of <?php echo ceil($total / $per_page); ?> (<?php echo $total; ?> transactions)</span>
        <nav class="flex items-center gap-1" aria-label="Pagination"><?php $base_params = array_map( 'sanitize_text_field', wp_unslash( $_GET ) ); unset($base_params['paged']); ?><a href="?<?php echo esc_attr( http_build_query(array_merge($base_params, ['paged' => $paged - 1])) ); ?>#transactions" class="<?php echo $paged > 1 ? 'inline-flex items-center px-3 py-1.5 rounded-lg border border-slate-300 bg-white hover:bg-slate-100' : 'inline-flex items-center px-3 py-1.5 rounded-lg border border-slate-200 bg-slate-100 text-slate-400'; ?>">&laquo; Prev</a><?php for ($i = 1; $i <= ceil($total / $per_page); $i++): ?><a href="?<?php echo esc_attr( http_build_query(array_merge($base_params, ['paged' => $i])) ); ?>#transactions" class="<?php echo $i == $paged ? 'inline-flex items-center px-3 py-1.5 rounded-lg border border-indigo-600 bg-indigo-600 text-white font-bold' : 'inline-flex items-center px-3 py-1.5 rounded-lg border border-slate-300 bg-white hover:bg-slate-100'; ?>"><?php echo esc_html( $i ); ?></a><?php endfor; ?><a href="?<?php echo esc_attr( http_build_query(array_merge($base_params, ['paged' => $paged + 1])) ); ?>#transactions" class="<?php echo $paged < ceil($total / $per_page) ? 'inline-flex items-center px-3 py-1.5 rounded-lg border border-slate-300 bg-white hover:bg-slate-100' : 'inline-flex items-center px-3 py-1.5 rounded-lg border border-slate-200 bg-slate-100 text-slate-400'; ?>">Next &raquo;</a></nav>
      </div>
    <?php endif; ?>
  </div>

  <!-- Modals (Styling unchanged, structure is fine) -->
  <div id="epa-details-modal" tabindex="-1" class="hidden fixed inset-0 z-50 w-full p-4 bg-black/50 flex items-center justify-center"><div class="relative w-full max-w-2xl"><div class="relative bg-white rounded-2xl shadow-2xl"><div class="flex items-center justify-between p-4 border-b rounded-t"><h3 class="text-xl font-semibold text-slate-800">Transaction Details</h3><button type="button" id="epa-details-modal-close-btn" class="text-slate-400 bg-transparent hover:bg-slate-200 hover:text-slate-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center"><svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg></button></div><div id="epa-details-content" class="p-6 text-sm text-slate-700" style="max-height:70vh; overflow:auto;"></div></div></div></div>
  <div id="epa-delete-modal" tabindex="-1" class="hidden fixed inset-0 z-50 w-full p-4 bg-black/50 flex items-center justify-center"><div class="relative w-full max-w-md"><div class="relative bg-white rounded-2xl shadow-2xl p-6 text-center"><h3 class="mb-4 text-lg font-semibold text-slate-800">Confirm Delete</h3><p class="mb-6 text-sm text-slate-600">Are you sure you want to delete this transaction? This action cannot be undone.</p><div class="flex justify-center gap-4"><button type="button" id="epa-delete-modal-cancel-btn" class="bg-slate-200 hover:bg-slate-300 text-slate-800 px-5 py-2.5 rounded-lg font-semibold">Cancel</button><button type="button" id="epa-delete-confirm-btn" class="bg-red-600 hover:bg-red-700 text-white px-5 py-2.5 rounded-lg font-semibold">Delete</button></div></div></div></div>
</div>

<!-- --- JavaScript Logic (FIXED & COMPLETE) --- -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
(function() {
    // --- Charting Data ---
    const revenueLabels = <?php echo wp_json_encode(array_map(fn($r) => $r['day'], $revenue_by_day)); ?>;
    const revenueSuccessRaw = <?php echo wp_json_encode(array_map(fn($r) => $r['success'] ?? 0, $revenue_by_day)); ?>;
    const revenuePendingRaw = <?php echo wp_json_encode(array_map(fn($r) => $r['pending'] ?? 0, $revenue_by_day)); ?>;
    const revenueFailedRaw = <?php echo wp_json_encode(array_map(fn($r) => $r['failed'] ?? 0, $revenue_by_day)); ?>;
    const toAmount = (v) => { const n = (typeof v === 'number') ? v : (v === null || v === '' ? 0 : parseFloat(v)); return Number.isFinite(n) ? n / 100 : 0; };
    const revenueSuccess = revenueSuccessRaw.map(toAmount);
    const revenuePending = revenuePendingRaw.map(toAmount);
    const revenueFailed = revenueFailedRaw.map(toAmount);
    const chartLocale = '<?php echo str_replace("_", "-", get_locale()); ?>';
    const chartCurrency = '<?php echo esc_js($chart_currency); ?>';
    const statusLabels = <?php echo wp_json_encode(array_keys($status_counts)); ?>;
    const statusData = <?php echo wp_json_encode(array_values($status_counts)); ?>;

    let revenueChart = null;
    let statusChart = null;

    // --- Chart Creation ---
    function createCharts() {
        if (typeof Chart === 'undefined') { console.warn('Chart.js not loaded.'); return; }
        try {
            const revCanvas = document.getElementById('epa-revenue-chart');
            if (revCanvas && !revenueChart) {
                revenueChart = new Chart(revCanvas.getContext('2d'), {
                    type: 'line', data: { labels: revenueLabels, datasets: [
                      { label: 'Success', data: revenueSuccess, borderColor: '#10B981', backgroundColor: 'rgba(16,185,129,0.06)', fill: false, tension: 0.3, pointRadius: 2 },
                      { label: 'Pending', data: revenuePending, borderColor: '#F59E0B', backgroundColor: 'rgba(245,158,11,0.06)', fill: false, tension: 0.3, pointRadius: 2 },
                      { label: 'Failed', data: revenueFailed, borderColor: '#EF4444', backgroundColor: 'rgba(239,68,68,0.06)', fill: false, tension: 0.3, pointRadius: 2 }
                    ] },
                    options: { scales: { y: { beginAtZero: true, ticks: { callback: v => new Intl.NumberFormat(chartLocale, { style: 'currency', currency: chartCurrency }).format(v) } } }, maintainAspectRatio: false, interaction: { intersect: false, mode: 'index' }, plugins: { legend: { display: true, position: 'bottom' }, tooltip: { callbacks: { label: ctx => ctx.dataset && ctx.dataset.label ? (ctx.dataset.label + ': ' + new Intl.NumberFormat(chartLocale, { style: 'currency', currency: chartCurrency }).format(ctx.parsed.y)) : new Intl.NumberFormat(chartLocale, { style: 'currency', currency: chartCurrency }).format(ctx.parsed.y) } } } }
                });
            }
            const stCanvas = document.getElementById('epa-status-chart');
            if (stCanvas && !statusChart) {
              // Build stable colors mapped by status name so single-status charts keep correct color
              var statusColorMap = { 'failed': '#EF4444', 'pending': '#F59E0B', 'success': '#10B981' };
              var defaultStatusColor = '#6B7280';
              var statusColors = statusLabels.map(function(s){
                return statusColorMap[(s || '').toLowerCase().trim()] || defaultStatusColor;
              });
              statusChart = new Chart(stCanvas.getContext('2d'), {
                type: 'doughnut', data: { labels: statusLabels, datasets: [{ data: statusData, backgroundColor: statusColors, borderWidth: 0 }] },
                options: { maintainAspectRatio: false, plugins: { legend: { position: 'bottom', labels: { padding: 15, boxWidth: 12, font: { size: 12 } } } } }
              });
            }
        } catch (err) { console.error('Error creating charts', err); }
    }

    // --- Tab & Panel Management ---
    function showPanel(tab) {
        const reportPanel = document.getElementById('epa-panel-report');
        const transactionsPanel = document.getElementById('epa-panel-transactions');
        const tabReport = document.getElementById('epa-tab-report');
        const tabTransactions = document.getElementById('epa-tab-transactions');

        [tabReport, tabTransactions].forEach(t => {
            t.setAttribute('aria-selected', 'false');
            t.classList.remove('bg-indigo-600', 'text-white', 'shadow');
            t.classList.add('text-slate-600', 'hover:bg-slate-100');
        });

        if (tab === 'transactions') {
            reportPanel.classList.add('hidden');
            transactionsPanel.classList.remove('hidden');
            tabTransactions.setAttribute('aria-selected', 'true');
            tabTransactions.classList.add('bg-indigo-600', 'text-white', 'shadow');
            tabTransactions.classList.remove('text-slate-600', 'hover:bg-slate-100');
        } else {
            reportPanel.classList.remove('hidden');
            transactionsPanel.classList.add('hidden');
            tabReport.setAttribute('aria-selected', 'true');
            tabReport.classList.add('bg-indigo-600', 'text-white', 'shadow');
            tabReport.classList.remove('text-slate-600', 'hover:bg-slate-100');
            createCharts();
            setTimeout(() => { // Allow time for DOM to render before resizing
                if (revenueChart) revenueChart.resize();
                if (statusChart) statusChart.resize();
            }, 0);
        }
    }

    // --- Event Listeners & Initializers ---
    function updateQueryStringParameter(uri, key, value) {
        const re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        const separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) { return uri.replace(re, '$1' + key + "=" + value + '$2'); }
        else { return uri + separator + key + "=" + value; }
    }

    document.getElementById('epa-tab-report').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', updateQueryStringParameter(window.location.href, 'tab', 'report')); showPanel('report'); });
    document.getElementById('epa-tab-transactions').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', updateQueryStringParameter(window.location.href, 'tab', 'transactions') + '#transactions'); showPanel('transactions'); });

    const params = new URLSearchParams(window.location.search);
    let initialTab = params.get('tab') || (window.location.hash === '#transactions' ? 'transactions' : 'report');
    showPanel(initialTab);

    // --- Report Filter Logic (FIXED) ---
    function formatDate(d) { return d.toISOString().slice(0, 10); }

    function applyRange(range) {
        const now = new Date(); let start, end;
        if (range === '7') { end = new Date(now); start = new Date(); start.setDate(end.getDate() - 6); } 
        else if (range === '30') { end = new Date(now); start = new Date(); start.setDate(end.getDate() - 29); } 
        else if (range === 'this_month') { start = new Date(now.getFullYear(), now.getMonth(), 1); end = new Date(now); } 
        else if (range === 'last_month') { const ym = new Date(now.getFullYear(), now.getMonth() - 1, 1); start = new Date(ym.getFullYear(), ym.getMonth(), 1); end = new Date(ym.getFullYear(), ym.getMonth() + 1, 0); } 
        
        let url = new URL(window.location.href);
        if (range === 'all') {
            url.searchParams.delete('date_start');
            url.searchParams.delete('date_end');
        } else if (start && end) {
            url.searchParams.set('date_start', formatDate(start));
            url.searchParams.set('date_end', formatDate(end));
        }
        url.searchParams.set('tab', 'report');
        window.location.href = url.pathname + url.search;
    }

    document.querySelectorAll('.epa-range-btn').forEach(btn => btn.addEventListener('click', function() { applyRange(this.getAttribute('data-range')); }));

    (function updateRangeLabelFromParams() {
        const ps = new URLSearchParams(window.location.search);
        const ds = ps.get('date_start'), de = ps.get('date_end');
        const labelEl = document.getElementById('epa-range-value');
        if (!labelEl) return;
        if (!ds && !de) { labelEl.textContent = 'All time'; }
        else if (ds && de) { labelEl.textContent = ds + ' → ' + de; }
        else if (ds) { labelEl.textContent = 'From ' + ds; }
        else if (de) { labelEl.textContent = 'Until ' + de; }
    })();

    // --- Other Listeners ---
    document.getElementById('epa-reset-filters').onclick = function() {
        const url = new URL(window.location.href);
        ['order_by', 'order_dir', 'search', 'status', 'date_start', 'date_end', 'paged'].forEach(p => url.searchParams.delete(p));
        url.searchParams.set('page', 'elementor-pay-addons-transactions');
        url.searchParams.set('tab', 'transactions'); // Stay on transactions tab
        window.location.href = url.pathname + '?' + url.searchParams.toString() + '#transactions';
    };

    window.addEventListener('resize', () => {
        if (revenueChart) revenueChart.resize();
        if (statusChart) statusChart.resize();
    });

})();
</script>
