<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();

if (!isLoggedIn()) {
    jsonResponse(['status' => 'error', 'message' => 'Unauthorized'], 401);
}

$user = getUserById($_SESSION['user_id']);
session_write_close();
$db = getDB();

$filter = $_GET['filter'] ?? 'all';
$search = trim($_GET['search'] ?? '');
$limit = (int)($_GET['limit'] ?? 25);
if (!in_array($limit, [10, 25, 50, 100])) $limit = 25;

$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$params = [$user['id']];
$where = "WHERE user_id = ?";

// Time Filter
$timeCondition = '';
switch ($filter) {
    case 'today':
        $timeCondition = "AND created_at_timestamp >= ?";
        $params[] = strtotime('today');
        break;
    case 'yesterday':
        $timeCondition = "AND created_at_timestamp >= ? AND created_at_timestamp < ?";
        $params[] = strtotime('yesterday');
        $params[] = strtotime('today');
        break;
    case '7days':
        $timeCondition = "AND created_at_timestamp >= ?";
        $params[] = strtotime('-7 days');
        break;
    case '1month':
        $timeCondition = "AND created_at_timestamp >= ?";
        $params[] = strtotime('-1 month');
        break;
    case '6months':
        $timeCondition = "AND created_at_timestamp >= ?";
        $params[] = strtotime('-6 months');
        break;
    case '1year':
        $timeCondition = "AND created_at_timestamp >= ?";
        $params[] = strtotime('-1 year');
        break;
}
$where .= " " . $timeCondition;

// Search Filter
if ($search !== '') {
    $where .= " AND (order_id LIKE ? OR utr LIKE ? OR sender_name LIKE ?)";
    $like = "%{$search}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

// 1. Get totals for the whole filtered set
$statsParams = $params;
$statsQuery = "SELECT 
    SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_count,
    SUM(CASE WHEN status = 'success' THEN amount ELSE 0 END) as total_revenue,
    SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_count
FROM orders $where";
$stmt = $db->prepare($statsQuery);
$stmt->execute($statsParams);
$stats = $stmt->fetch();
$successCount = (int)($stats['success_count'] ?? 0);
$totalRevenue = (float)($stats['total_revenue'] ?? 0);
$failedCount = (int)($stats['failed_count'] ?? 0);

// 2. Get total pages for pagination (counting all statuses)
$countQuery = "SELECT COUNT(*) as total_rows FROM orders $where";
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalRows = (int)$stmt->fetchColumn();
$totalPages = ceil($totalRows / $limit);
if ($totalPages < 1) $totalPages = 1;

// 3. Fetch actual data for this page
$query = "SELECT * FROM orders $where ORDER BY created_at_timestamp DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

// 4. Build HTML
$html = '';
if (count($transactions) > 0) {
    foreach ($transactions as $tx) {
        $statusClass = 'status-pending';
        $statusText = 'Pending';
        if ($tx['status'] === 'success') {
            $statusClass = 'status-success';
            $statusText = 'Success';
        } elseif ($tx['status'] === 'failed') {
            $statusClass = 'status-failed';
            $statusText = 'Failed';
        } elseif ($tx['status'] === 'expired') {
            $statusClass = 'status-expired';
            $statusText = 'Expired';
        }

        $orderIdHtml = htmlspecialchars($tx['order_id']);
        if ($tx['type'] === 'payment_link') {
            $orderIdHtml .= '<div style="font-size:11px; color:var(--color-primary); margin-top:2px;"><i data-lucide="link" style="width:10px;height:10px;display:inline-block;vertical-align:middle;"></i> Payment Link</div>';
        }

        $amt = number_format($tx['payable_amount'] ?: $tx['amount'], 2);
        $base = '';
        if ($tx['payable_amount'] && $tx['payable_amount'] != $tx['amount']) {
            $baseAmt = number_format($tx['amount'], 2);
            $base = "<div style=\"font-size:11px; color:var(--color-ink-mute);\">Base: ₹{$baseAmt}</div>";
        }

        $date1 = date('d M Y', $tx['created_at_timestamp']);
        $date2 = date('h:i A', $tx['created_at_timestamp']);

        $utr = $tx['utr'] ? htmlspecialchars($tx['utr']) : '<span style="color:var(--color-ink-mute); font-size:12px;">N/A</span>';
        
        $payerHtml = '';
        if ($tx['sender_name']) {
            $payerHtml .= '<div style="font-size:13px; font-weight:600; color:var(--color-primary);">' . htmlspecialchars($tx['sender_name']) . ' (UPI)</div>';
        }
        if ($tx['customer_name']) {
            $payerHtml .= '<div style="font-size:13px; font-weight:600;">' . htmlspecialchars($tx['customer_name']) . '</div>';
        }
        if ($tx['customer_email']) {
            $payerHtml .= '<div style="font-size:12px; color:var(--color-ink-mute);">' . htmlspecialchars($tx['customer_email']) . '</div>';
        }
        if ($tx['customer_phone']) {
            $payerHtml .= '<div style="font-size:12px; color:var(--color-ink-mute);">' . htmlspecialchars($tx['customer_phone']) . '</div>';
        }
        if (empty($payerHtml)) {
            $payerHtml = '<span style="color:var(--color-ink-mute); font-size:12px;">N/A</span>';
        }

        $html .= "
        <tr>
            <td>
                <div style=\"font-weight:700; font-family:monospace; font-size:13px;\">{$orderIdHtml}</div>
            </td>
            <td>
                <div style=\"font-weight:700;\">₹{$amt}</div>
                {$base}
            </td>
            <td><span class=\"status-badge {$statusClass}\">{$statusText}</span></td>
            <td>
                <div style=\"font-size:13px; font-weight:500;\">{$date1}</div>
                <div style=\"font-size:12px; color:var(--color-ink-mute);\">{$date2}</div>
            </td>
            <td><div style=\"font-weight:600; font-size:13px; font-family:monospace;\">{$utr}</div></td>
            <td><div style=\"font-size:13px; font-weight:600; display:flex; flex-direction:column; gap:2px;\">{$payerHtml}</div></td>
        </tr>";
    }
} else {
    // Empty state is handled by JS frontend now
}

echo json_encode([
    'status' => 'success',
    'html' => $html,
    'successCount' => number_format($successCount),
    'failedCount' => number_format($failedCount),
    'totalRevenue' => '₹' . number_format($totalRevenue, 2),
    'totalPages' => $totalPages,
    'currentPage' => $page,
    'totalRows' => $totalRows
]);
