<?php include "header.php"; ?>

<?php
// Self-healing auto-expiry: any order that's still PENDING but whose payment
// link is older than 5 minutes is treated as failed, regardless of whether
// the customer's browser ever reported it. Runs every time this list loads.
$conn->query("
    UPDATE orders o
    JOIN payment_links pl ON pl.order_id = o.order_id
    SET o.status = 'FAILURE'
    WHERE o.status = 'PENDING'
      AND pl.created_at < (NOW() - INTERVAL 5 MINUTE)
");

// WhatsApp API Configuration
$apiKey = "bSVJcHDwZeUqkBBlvHZRvn3xuVT7jX";
$sender = "6200218694";
$logFile = "whatsapp_messages.log";

// Function to send WhatsApp message and log it
function sendWhatsAppNotification($mobile, $message, $order_id) {
    global $apiKey, $sender, $logFile, $conn;

    // Check if this order ID was already notified
    $check_query = "SELECT COUNT(*) as count FROM whatsapp_logs WHERE order_id = '$order_id'";
    $result = mysqli_query($conn, $check_query);
    $row = mysqli_fetch_assoc($result);

    if ($row['count'] > 0) {
        return false; // Already notified
    }

    // Encode message for URL
    $encodedMsg = urlencode($message);
    $url = "https://wa.indiaapi.shop/send-message?api_key=$apiKey&sender=$sender&number=91$mobile&message=$encodedMsg";

    // Send request to WhatsApp API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    // Log the message in database
    $log_query = "INSERT INTO whatsapp_logs (mobile, message, order_id, sent_time)
                  VALUES ('$mobile', '".mysqli_real_escape_string($conn, $message)."', '$order_id', NOW())";
    mysqli_query($conn, $log_query);

    // Log to file
    $logEntry = date("Y-m-d H:i:s") . " | Order ID: $order_id | Mobile: $mobile | Message: $message\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);

    return true;
}

// ---- Build the rows once into an array (same data, same permissions logic)
// so we can both (a) render the table and (b) compute quick summary counts
// without querying twice. ----
$rows = [];
if ($userdata['role'] == 'User') {
    $token = $userdata['user_token'];
    $query = "SELECT `id`, `create_date`, `gateway_txn`, `customer_mobile`, `method`, `utr`, `byteTransactionId`, `order_id`, `amount`, `status`, `is_test`, `redirect_url` FROM `orders` WHERE user_token = '$token' ORDER BY `create_date` DESC";
} else {
    $query = "SELECT * FROM `orders` ORDER BY id DESC";
}
$query_run = mysqli_query($conn, $query);
if ($query_run) {
    while ($r = mysqli_fetch_assoc($query_run)) {
        $rows[] = $r;
    }
}

$sumSuccess = 0; $sumPending = 0; $sumFailed = 0; $cntSuccess = 0; $cntPending = 0; $cntFailed = 0;
foreach ($rows as $r) {
    if ($r['status'] == 'SUCCESS') { $sumSuccess += (float)$r['amount']; $cntSuccess++; }
    elseif ($r['status'] == 'PENDING') { $sumPending += (float)$r['amount']; $cntPending++; }
    elseif ($r['status'] == 'FAILURE') { $sumFailed += (float)$r['amount']; $cntFailed++; }
}
$totalCount = count($rows);
$successRatePct = $totalCount > 0 ? round(($cntSuccess / $totalCount) * 100, 1) : 0;
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link href="./assets/vendors/DataTables/datatables.min.css" rel="stylesheet" />

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}
    ::-webkit-scrollbar{width:8px;height:8px}
    ::-webkit-scrollbar-track{background:transparent}
    ::-webkit-scrollbar-thumb{background:rgba(255,255,255,.12);border-radius:10px}
    ::-webkit-scrollbar-thumb:hover{background:rgba(255,255,255,.22)}

    .txn-wrap{padding:20px;max-width:1440px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .txn-head{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-bottom:22px}
    .txn-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .txn-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .txn-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}
    .head-actions{display:flex;gap:10px;flex-wrap:wrap}

    .btn-ghost{
        background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#fff;
        padding:9px 16px;border-radius:10px;font-size:.82rem;font-weight:600;cursor:pointer;
        display:inline-flex;align-items:center;gap:7px;transition:.2s;
    }
    .btn-ghost:hover{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.2);color:#fff;transform:translateY(-1px)}
    .btn-primary{
        background:var(--g);border:none;color:#fff;padding:9px 16px;border-radius:10px;
        font-size:.82rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:7px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);
    }
    .btn-primary:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}

    /* ---- Mini stat cards, now clickable filters ---- */
    .mini-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:22px}
    .mini-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:16px 18px;
        display:flex;align-items:center;gap:12px;transition:.25s;cursor:pointer;position:relative;overflow:hidden;
    }
    .mini-card::after{
        content:'';position:absolute;inset:0;border-radius:16px;padding:1px;
        background:var(--g);opacity:0;transition:.25s;
        -webkit-mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);
        -webkit-mask-composite:xor;mask-composite:exclude;pointer-events:none;
    }
    .mini-card:hover{transform:translateY(-4px);border-color:rgba(108,99,255,.35)}
    .mini-card.active{background:rgba(108,99,255,.08);border-color:rgba(108,99,255,.5)}
    .mini-card.active::after{opacity:1}
    .mini-ic{width:42px;height:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:16px;color:#fff;flex-shrink:0}
    .mini-ic.total{background:var(--g)}
    .mini-ic.success{background:linear-gradient(135deg,#0f5132,#43e97b)}
    .mini-ic.pending{background:linear-gradient(135deg,#7c4a03,#f5b93b)}
    .mini-ic.failed{background:linear-gradient(135deg,#7f1d3a,#ff6584)}
    .mini-val{font-size:1.15rem;font-weight:800;color:#fff;line-height:1.2}
    .mini-label{font-size:.72rem;color:rgba(255,255,255,.45);font-weight:500;display:flex;align-items:center;gap:6px}
    .mini-sub{font-size:.68rem;color:rgba(255,255,255,.3)}

    .dashboard-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
    }
    .card-header{
        padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.07);
        display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;
    }
    .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff;display:flex;align-items:center;gap:8px}
    .live-dot{width:7px;height:7px;border-radius:50%;background:var(--success);box-shadow:0 0 0 rgba(67,233,123,.6);animation:pulse 2s infinite}
    @keyframes pulse{0%{box-shadow:0 0 0 0 rgba(67,233,123,.55)}70%{box-shadow:0 0 0 8px rgba(67,233,123,0)}100%{box-shadow:0 0 0 0 rgba(67,233,123,0)}}
    .card-body{padding:10px 22px 22px}

    .toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:6px}
    .filter-tabs{display:flex;gap:6px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);padding:4px;border-radius:12px}
    .filter-tab{
        padding:7px 14px;border-radius:9px;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);
        cursor:pointer;transition:.2s;white-space:nowrap;
    }
    .filter-tab:hover{color:#fff}
    .filter-tab.active{background:var(--g);color:#fff;box-shadow:0 4px 14px rgba(108,99,255,.35)}

    .search-box{position:relative}
    .search-box i{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3);font-size:13px}
    .search-box input{
        background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:10px;
        padding:9px 12px 9px 34px;color:#fff;font-size:13px;outline:none;min-width:230px;transition:.2s;
    }
    .search-box input:focus{border-color:var(--p);background:rgba(108,99,255,.08)}
    .search-box input::placeholder{color:rgba(255,255,255,.25)}

    /* status pills */
    .pill{
        display:inline-flex;align-items:center;gap:5px;padding:5px 11px;border-radius:20px;
        font-size:.72rem;font-weight:700;letter-spacing:.2px;
    }
    .pill i{font-size:.65rem}
    .pill-success{background:rgba(67,233,123,.13);color:var(--success)}
    .pill-danger{background:rgba(255,101,132,.13);color:var(--danger)}
    .pill-warning{background:rgba(245,185,59,.15);color:var(--warning)}
    .test-tag{font-size:9px;font-weight:700;color:#0a0a12;background:var(--warning);padding:2px 6px;border-radius:5px;margin-left:6px;vertical-align:middle}

    .mono{font-family:'JetBrains Mono',monospace;font-size:.78rem;color:rgba(255,255,255,.65)}
    .amt{font-weight:700;color:#fff}

    .copy-wrap{display:inline-flex;align-items:center;gap:6px}
    .copy-btn{
        background:transparent;border:none;color:rgba(255,255,255,.25);cursor:pointer;font-size:11px;
        padding:2px;transition:.15s;
    }
    .copy-btn:hover{color:var(--p)}
    .copy-btn.copied{color:var(--success)}

    .avatar-chip{
        width:28px;height:28px;border-radius:8px;background:rgba(108,99,255,.15);color:var(--p);
        display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;
        margin-right:8px;flex-shrink:0;
    }

    /* DataTables overrides for dark theme */
    table.dataTable{color:#fff !important;border-collapse:separate !important;border-spacing:0}
    table.dataTable thead th{
        color:rgba(255,255,255,.45) !important;font-size:.72rem;text-transform:uppercase;letter-spacing:.5px;
        border-bottom:1px solid rgba(255,255,255,.08) !important;padding:12px 14px !important;font-weight:700;
        white-space:nowrap;
    }
    table.dataTable tbody td{
        border-bottom:1px solid rgba(255,255,255,.05) !important;padding:12px 14px !important;
        font-size:.85rem;color:rgba(255,255,255,.85);vertical-align:middle;
    }
    table.dataTable tbody tr{transition:.15s;animation:rowIn .35s ease both}
    @keyframes rowIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
    table.dataTable tbody tr:hover{background:rgba(108,99,255,.06) !important}
    table.dataTable tbody tr.odd, table.dataTable tbody tr.even{background:transparent !important}
    .dataTables_wrapper .dataTables_filter,
    .dataTables_wrapper .dataTables_length{display:none}
    .dataTables_wrapper .dataTables_info{color:rgba(255,255,255,.4) !important;font-size:.78rem;padding-top:14px !important}
    .dataTables_wrapper .dataTables_paginate .paginate_button{
        color:rgba(255,255,255,.6) !important;border-radius:8px !important;border:1px solid transparent !important;
        padding:5px 11px !important;margin-left:4px !important;
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.current{
        background:var(--g) !important;color:#fff !important;border:none !important;
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button:hover{
        background:rgba(255,255,255,.08) !important;color:#fff !important;
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.disabled{opacity:.3}

    .empty-state{text-align:center;padding:60px 20px;color:rgba(255,255,255,.35)}
    .empty-state i{font-size:2.4rem;margin-bottom:14px;display:block;color:rgba(255,255,255,.15)}
    .empty-state h4{color:rgba(255,255,255,.55);font-size:1rem;margin-bottom:6px}

    .toast-copy{
        position:fixed;bottom:24px;left:50%;transform:translateX(-50%) translateY(20px);
        background:rgba(20,20,30,.95);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.12);
        color:#fff;padding:11px 20px;border-radius:12px;font-size:.82rem;font-weight:600;
        display:flex;align-items:center;gap:8px;opacity:0;transition:.25s;z-index:9999;pointer-events:none;
        box-shadow:0 12px 30px rgba(0,0,0,.4);
    }
    .toast-copy.show{opacity:1;transform:translateX(-50%) translateY(0)}
    .toast-copy i{color:var(--success)}

    /* ---- Mobile card view (replaces table on small screens) ---- */
    .mobile-cards{display:none}
    @media(max-width:768px){
        .mini-stats{grid-template-columns:repeat(2,1fr)}
        .card-body{padding:10px 12px 18px}
        .search-box input{min-width:100%;width:100%}
        .toolbar{flex-direction:column;align-items:stretch}
        .filter-tabs{overflow-x:auto}
        .txn-head p{margin-left:0}

        .table-responsive{display:none}
        .mobile-cards{display:block}
        .txn-card{
            background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:14px;
            padding:14px;margin-bottom:10px;animation:rowIn .3s ease both;
        }
        .txn-card-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px}
        .txn-card-row{display:flex;justify-content:space-between;font-size:.78rem;padding:4px 0;color:rgba(255,255,255,.55)}
        .txn-card-row span:last-child{color:#fff;font-weight:600}
    }
    .action-btn{padding:6px 12px;font-size:.74rem}

    /* ---- Glassmorphism "Change Payment Status" modal (matches page theme) ---- */
    .swal-glass-popup{
        background:rgba(24,22,38,.68) !important;
        backdrop-filter:blur(28px) saturate(180%);
        -webkit-backdrop-filter:blur(28px) saturate(180%);
        border:1px solid rgba(255,255,255,.14) !important;
        border-radius:22px !important;
        box-shadow:0 24px 70px rgba(0,0,0,.55), inset 0 1px 0 rgba(255,255,255,.08) !important;
        color:#fff !important;
    }
    .swal-glass-popup .swal2-title{color:#fff !important;font-weight:800}
    .swal-glass-popup .swal2-html-container{color:rgba(255,255,255,.65) !important}
    .swal-glass-popup .swal2-close{color:rgba(255,255,255,.5) !important}
    .swal-glass-popup .swal2-close:hover{color:#fff !important}
    .swal-glass-popup .swal2-validation-message{
        background:rgba(255,101,132,.12) !important;color:#ff98ac !important;
        border:1px solid rgba(255,101,132,.3) !important;
    }
    .swal-glass-popup .swal2-timer-progress-bar{background:var(--g) !important}

    .status-choice-wrap{display:flex;gap:12px;justify-content:center;margin-top:8px}
    .status-choice{
        flex:1;max-width:140px;padding:20px 12px;border-radius:16px;
        border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.05);
        backdrop-filter:blur(10px);cursor:pointer;text-align:center;
        transition:.2s;position:relative;overflow:hidden;
    }
    .status-choice:hover{transform:translateY(-2px);background:rgba(255,255,255,.08)}
    .status-choice i{font-size:26px;display:block;margin-bottom:8px}
    .status-choice span{font-size:13px;font-weight:700;color:rgba(255,255,255,.75)}
    .status-choice.success-choice i{color:var(--success)}
    .status-choice.failed-choice i{color:var(--danger)}
    .status-choice.selected.success-choice{
        border-color:var(--success);background:rgba(67,233,123,.12);
        box-shadow:0 0 0 1px rgba(67,233,123,.4), 0 8px 22px rgba(67,233,123,.2);
    }
    .status-choice.selected.failed-choice{
        border-color:var(--danger);background:rgba(255,101,132,.12);
        box-shadow:0 0 0 1px rgba(255,101,132,.4), 0 8px 22px rgba(255,101,132,.2);
    }
    .status-choice.selected span{color:#fff}

    .swal-glass-confirm, .swal-glass-cancel{
        padding:10px 22px;border-radius:10px;font-size:.85rem;font-weight:700;
        cursor:pointer;transition:.2s;margin:0 6px;border:none;
    }
    .swal-glass-confirm{background:var(--g) !important;color:#fff !important;box-shadow:0 6px 18px rgba(108,99,255,.35)}
    .swal-glass-confirm:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.5)}
    .swal-glass-cancel{background:rgba(255,255,255,.07) !important;color:#fff !important;border:1px solid rgba(255,255,255,.14) !important}
    .swal-glass-cancel:hover{background:rgba(255,255,255,.12) !important}
    .swal-glass-deny{background:rgba(255,101,132,.15) !important;color:#ff98ac !important;border:1px solid rgba(255,101,132,.35) !important}

    /* ---- Order Details view modal ---- */
    .od-section{
        background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.1);
        border-radius:14px;padding:14px 16px;margin-bottom:12px;text-align:left;
    }
    .od-section-title{
        font-size:.72rem;font-weight:800;text-transform:uppercase;letter-spacing:.6px;
        color:rgba(255,255,255,.4);margin-bottom:10px;display:flex;align-items:center;gap:7px;
    }
    .od-row{display:flex;justify-content:space-between;align-items:center;padding:7px 0;
        border-bottom:1px solid rgba(255,255,255,.06);gap:14px}
    .od-row:last-child{border-bottom:none}
    .od-label{font-size:.78rem;color:rgba(255,255,255,.5);flex-shrink:0}
    .od-value{font-size:.83rem;color:#fff;font-weight:600;text-align:right;word-break:break-all}
    .od-open{
        color:#a99bff;text-decoration:none;font-size:.78rem;font-weight:700;
        display:inline-flex;align-items:center;gap:5px;white-space:nowrap;
    }
    .od-open:hover{color:#c9befc}
    .od-open.disabled{color:rgba(255,255,255,.25);pointer-events:none}
</style>

<div class="txn-wrap">
    <div class="txn-head">
        <div>
            <h1><span class="icn"><i class="fas fa-receipt"></i></span>Transactions</h1>
            <p>Complete history of every payment attempt on your account</p>
        </div>
        <div class="head-actions">
            <button class="btn-ghost" id="exportCsv"><i class="fas fa-download"></i> Export CSV</button>
            <button class="btn-primary" id="refreshBtn"><i class="fas fa-rotate"></i> Refresh</button>
        </div>
    </div>

    <div class="mini-stats">
        <div class="mini-card active" data-filter="all">
            <div class="mini-ic total"><i class="fas fa-layer-group"></i></div>
            <div><div class="mini-val"><?php echo number_format($totalCount); ?></div><div class="mini-label">Total Transactions</div></div>
        </div>
        <div class="mini-card" data-filter="Success">
            <div class="mini-ic success"><i class="fas fa-check"></i></div>
            <div><div class="mini-val">₹<?php echo number_format($sumSuccess, 2); ?></div><div class="mini-label"><?php echo $cntSuccess; ?> Successful <span class="mini-sub">(<?php echo $successRatePct; ?>%)</span></div></div>
        </div>
        <div class="mini-card" data-filter="Pending">
            <div class="mini-ic pending"><i class="fas fa-hourglass-half"></i></div>
            <div><div class="mini-val">₹<?php echo number_format($sumPending, 2); ?></div><div class="mini-label"><?php echo $cntPending; ?> Pending</div></div>
        </div>
        <div class="mini-card" data-filter="Failed">
            <div class="mini-ic failed"><i class="fas fa-xmark"></i></div>
            <div><div class="mini-val">₹<?php echo number_format($sumFailed, 2); ?></div><div class="mini-label"><?php echo $cntFailed; ?> Failed</div></div>
        </div>
    </div>

    <div class="dashboard-card">
        <div class="card-header">
            <h3><span class="live-dot"></span> All Transactions</h3>
        </div>
        <div class="card-body">
            <div class="toolbar">
                <div class="filter-tabs">
                    <div class="filter-tab active" data-filter="all">All</div>
                    <div class="filter-tab" data-filter="Success">Success</div>
                    <div class="filter-tab" data-filter="Pending">Pending</div>
                    <div class="filter-tab" data-filter="Failed">Failed</div>
                </div>
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="txnSearch" placeholder="Search order id, mobile, RRN...">
                </div>
            </div>

            <?php if ($totalCount === 0): ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h4>No transactions yet</h4>
                    <p>Once payments start coming in, they'll show up here.</p>
                </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table" id="example-table" style="width:100%">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Mobile</th>
                            <th>Date Time</th>
                            <th>Merchant</th>
                            <th>Gateway Txn</th>
                            <th>Bank RRN</th>
                            <th>Order ID</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Details</th>
                            <?php if ($userdata['role'] == 'Admin' || $userdata['role'] == 'User'): ?><th>Action</th><?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($rows as $row):
                        if ($row['status'] == 'SUCCESS') {
                            $pillClass = 'pill-success'; $icon = 'fa-check'; $sts = 'Success';
                            // Prepare WhatsApp message with emojis and formatting
                            $date = date("d M Y", strtotime($row['create_date']));
                            $time = date("h:i A", strtotime($row['create_date']));
                            $message  = "🟢 *Payment Successful!*\n\n";
                            $message .= "🏷️ *Merchant:* " . $row['method'] . "\n";
                            $message .= "💰 *Amount:* ₹" . $row['amount'] . "\n";
                            $message .= "🧾 *Order ID:* " . $row['order_id'] . "\n";
                            $message .= "📅 *Date:* " . $date . "\n";
                            $message .= "⏰ *Time:* " . $time . "\n\n";
                            $message .= "🔋 *Powered by PayIndia™*\n";
                            $message .= "🙏 Thank you for your payment.";
                            if ($userdata['role'] == 'User') {
                                sendWhatsAppNotification($row['customer_mobile'], $message, $row['order_id']);
                            }
                        } elseif ($row['status'] == 'FAILURE') {
                            $pillClass = 'pill-danger'; $icon = 'fa-xmark'; $sts = 'Failed';
                        } else {
                            $pillClass = 'pill-warning'; $icon = 'fa-hourglass-half'; $sts = 'Pending';
                        }
                        $mobileSafe = htmlspecialchars($row['customer_mobile']);
                        $orderSafe  = htmlspecialchars($row['order_id']);
                        $rrnSafe    = htmlspecialchars($row['utr']);
                        $initials   = strtoupper(substr($mobileSafe, -2));
                    ?>
                        <tr data-status="<?php echo $sts; ?>">
                            <td class="mono">#<?php echo htmlspecialchars($row['id']); ?></td>
                            <td><span class="avatar-chip"><?php echo $initials; ?></span><span class="mono"><?php echo $mobileSafe; ?></span></td>
                            <td><?php echo htmlspecialchars($row['create_date']); ?></td>
                            <td><?php echo htmlspecialchars($row['method']); ?></td>
                            <td class="mono"><?php echo htmlspecialchars($row['gateway_txn']); ?></td>
                            <td>
                                <span class="copy-wrap">
                                    <span class="mono"><?php echo $rrnSafe; ?></span>
                                    <?php if ($rrnSafe !== ''): ?><button class="copy-btn" data-copy="<?php echo $rrnSafe; ?>"><i class="fas fa-copy"></i></button><?php endif; ?>
                                </span>
                            </td>
                            <td>
                                <span class="copy-wrap">
                                    <span class="mono"><?php echo $orderSafe; ?></span>
                                    <button class="copy-btn" data-copy="<?php echo $orderSafe; ?>"><i class="fas fa-copy"></i></button>
                                    <?php if (!empty($row['is_test'])): ?><span class="test-tag">TEST</span><?php endif; ?>
                                </span>
                            </td>
                            <td class="amt">₹<?php echo htmlspecialchars(number_format((float)$row['amount'], 2)); ?></td>
                            <td><span class="pill <?php echo $pillClass; ?>"><i class="fas <?php echo $icon; ?>"></i> <?php echo $sts; ?></span></td>
                            <td>
                                <button class="btn-ghost view-btn" data-order='<?php echo htmlspecialchars(json_encode([
                                    "order_id"   => $row['order_id'],
                                    "mobile"     => $row['customer_mobile'],
                                    "method"     => $row['method'],
                                    "amount"     => number_format((float)$row['amount'], 2),
                                    "status"     => $sts,
                                    "date"       => $row['create_date'],
                                    "gateway_txn"=> $row['gateway_txn'],
                                    "utr"        => $row['utr'],
                                    "redirect_url" => $row['redirect_url'] ?? '',
                                    "is_test"    => !empty($row['is_test']),
                                ]), ENT_QUOTES); ?>'><i class="fas fa-eye"></i> View</button>
                            </td>
                            <?php if ($userdata['role'] == 'Admin'): ?>
                            <td>
                                <?php if ($sts === 'Pending'): ?>
                                <button class="btn-ghost action-btn" onclick="changeOrderStatus('<?php echo $orderSafe; ?>')"><i class="fas fa-edit"></i> Action</button>
                                <?php else: ?>
                                <span class="mono" style="opacity:.3">—</span>
                                <?php endif; ?>
                            </td>
                            <?php elseif ($userdata['role'] == 'User'): ?>
                            <td>
                                <?php if ($sts === 'Pending' && !empty($row['is_test'])): ?>
                                <button class="btn-ghost action-btn" onclick="changeOrderStatus('<?php echo $orderSafe; ?>')" title="Resolve this test order to trigger your webhook"><i class="fas fa-edit"></i> Action</button>
                                <?php else: ?>
                                <span class="mono" style="opacity:.3">—</span>
                                <?php endif; ?>
                            </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Mobile-only stacked card view (same data, phone-friendly) -->
            <div class="mobile-cards">
                <?php foreach ($rows as $row):
                    if ($row['status'] == 'SUCCESS') { $pillClass = 'pill-success'; $icon = 'fa-check'; $sts = 'Success'; }
                    elseif ($row['status'] == 'FAILURE') { $pillClass = 'pill-danger'; $icon = 'fa-xmark'; $sts = 'Failed'; }
                    else { $pillClass = 'pill-warning'; $icon = 'fa-hourglass-half'; $sts = 'Pending'; }
                ?>
                    <div class="txn-card" data-status="<?php echo $sts; ?>">
                        <div class="txn-card-top">
                            <span class="mono">#<?php echo htmlspecialchars($row['id']); ?> · <?php echo htmlspecialchars($row['customer_mobile']); ?></span>
                            <span class="pill <?php echo $pillClass; ?>"><i class="fas <?php echo $icon; ?>"></i> <?php echo $sts; ?></span>
                        </div>
                        <div class="txn-card-row"><span>Amount</span><span>₹<?php echo number_format((float)$row['amount'], 2); ?></span></div>
                        <div class="txn-card-row"><span>Order ID</span><span><?php echo htmlspecialchars($row['order_id']); ?><?php if (!empty($row['is_test'])): ?><span class="test-tag">TEST</span><?php endif; ?></span></div>
                        <div class="txn-card-row"><span>Merchant</span><span><?php echo htmlspecialchars($row['method']); ?></span></div>
                        <div class="txn-card-row"><span>Date</span><span><?php echo htmlspecialchars($row['create_date']); ?></span></div>
                        <div style="margin-top:10px;text-align:right;display:flex;gap:8px;justify-content:flex-end;">
                            <button class="btn-ghost view-btn" data-order='<?php echo htmlspecialchars(json_encode([
                                "order_id"   => $row['order_id'],
                                "mobile"     => $row['customer_mobile'],
                                "method"     => $row['method'],
                                "amount"     => number_format((float)$row['amount'], 2),
                                "status"     => $sts,
                                "date"       => $row['create_date'],
                                "gateway_txn"=> $row['gateway_txn'],
                                "utr"        => $row['utr'],
                                "redirect_url" => $row['redirect_url'] ?? '',
                                "is_test"    => !empty($row['is_test']),
                            ]), ENT_QUOTES); ?>'><i class="fas fa-eye"></i> View</button>
                            <?php if ($userdata['role'] == 'Admin' && $sts === 'Pending'): ?>
                            <button class="btn-ghost action-btn" onclick="changeOrderStatus('<?php echo htmlspecialchars($row['order_id']); ?>')"><i class="fas fa-edit"></i> Action</button>
                            <?php elseif ($userdata['role'] == 'User' && $sts === 'Pending' && !empty($row['is_test'])): ?>
                            <button class="btn-ghost action-btn" onclick="changeOrderStatus('<?php echo htmlspecialchars($row['order_id']); ?>')" title="Resolve this test order to trigger your webhook"><i class="fas fa-edit"></i> Action</button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="toast-copy" id="copyToast"><i class="fas fa-circle-check"></i> <span id="copyToastText">Copied to clipboard</span></div>

<!-- JavaScript dependencies -->
<script src="./assets/vendors/jquery/dist/jquery.min.js"></script>
<script src="./assets/vendors/popper.js/dist/umd/popper.min.js"></script>
<script src="./assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="./assets/vendors/metisMenu/dist/metisMenu.min.js"></script>
<script src="./assets/vendors/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<script src="./assets/js/scripts/dashboard_1_demo.js"></script>
<script src="./assets/vendors/DataTables/datatables.min.js"></script>
<script src="assets/js/app.min.js"></script>
<script>
$(function() {
    var table = $('#example-table').DataTable({
        pageLength: 10,
        order: [[0, "desc"]],
        dom: 't<"d-flex justify-content-between align-items-center flex-wrap gap-2 mt-2"ip>'
    });

    // live text search (order id / mobile / RRN / anything in the row)
    $('#txnSearch').on('keyup', function() {
        table.search(this.value).draw();
        applyMobileCardSearch(this.value);
    });

    // status filter chips (both the mini-stat cards and the tab pills drive the same filter)
    function setFilter(status) {
        $('.filter-tab').removeClass('active').filter('[data-filter="' + status + '"]').addClass('active');
        $('.mini-card').removeClass('active').filter('[data-filter="' + status + '"]').addClass('active');

        if (status === 'all') {
            table.column(8).search('').draw();
        } else {
            table.column(8).search(status, true, false).draw();
        }
        $('.mobile-cards .txn-card').each(function() {
            var show = (status === 'all') || ($(this).data('status') == status);
            $(this).toggle(show);
        });
    }
    $('.filter-tab, .mini-card').on('click', function() {
        setFilter($(this).data('filter'));
    });

    function applyMobileCardSearch(term) {
        term = (term || '').toLowerCase();
        $('.mobile-cards .txn-card').each(function() {
            var text = $(this).text().toLowerCase();
            $(this).toggle(text.indexOf(term) !== -1);
        });
    }

    // copy-to-clipboard buttons
    $(document).on('click', '.copy-btn', function() {
        var val = $(this).data('copy');
        if (!val) return;
        navigator.clipboard.writeText(String(val)).then(function() {
            showToast('Copied "' + val + '"');
        });
        var $btn = $(this);
        $btn.addClass('copied');
        setTimeout(function() { $btn.removeClass('copied'); }, 1200);
    });

    function showToast(text) {
        $('#copyToastText').text(text);
        var $t = $('#copyToast').addClass('show');
        clearTimeout(window.__toastTimer);
        window.__toastTimer = setTimeout(function() { $t.removeClass('show'); }, 1800);
    }

    // ---- View order details (glass modal, built from the row's own data
    // - no extra request needed since it's already rendered on the page) ----
    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            let d;
            try { d = JSON.parse(btn.getAttribute('data-order')); } catch (e) { return; }

            const statusPillColor = d.status === 'Success' ? 'var(--success)' : (d.status === 'Failed' ? 'var(--danger)' : 'var(--warning)');
            const openLink = (label, statusParam) => {
                if (!d.redirect_url) {
                    return `<div class="od-row"><span class="od-label">${label}</span><span class="od-open disabled"><i class="fas fa-ban"></i> Not set</span></div>`;
                }
                const sep = d.redirect_url.includes('?') ? '&' : '?';
                const url = d.redirect_url + sep + 'payment_status=' + statusParam + '&order_id=' + encodeURIComponent(d.order_id);
                return `<div class="od-row"><span class="od-label">${label}</span><a class="od-open" href="${url}" target="_blank" rel="noopener"><i class="fas fa-arrow-up-right-from-square"></i> Open</a></div>`;
            };

            Swal.fire({
                title: 'Order Details',
                width: 420,
                html: `
                    <div class="od-section">
                        <div class="od-section-title"><i class="fas fa-circle-info"></i> Basic Information</div>
                        <div class="od-row"><span class="od-label">Order ID</span><span class="od-value">${d.order_id}${d.is_test ? ' <span class="test-tag">TEST</span>' : ''}</span></div>
                        <div class="od-row"><span class="od-label">Merchant</span><span class="od-value">${d.method || '—'}</span></div>
                        <div class="od-row"><span class="od-label">Mobile</span><span class="od-value">${d.mobile || '—'}</span></div>
                        <div class="od-row"><span class="od-label">Date &amp; Time</span><span class="od-value">${d.date}</span></div>
                        <div class="od-row"><span class="od-label">Amount</span><span class="od-value">₹${d.amount}</span></div>
                        <div class="od-row"><span class="od-label">Status</span><span class="od-value" style="color:${statusPillColor}">${d.status}</span></div>
                    </div>
                    <div class="od-section">
                        <div class="od-section-title"><i class="fas fa-receipt"></i> Transaction Details</div>
                        <div class="od-row"><span class="od-label">Gateway Txn</span><span class="od-value">${d.gateway_txn || '—'}</span></div>
                        <div class="od-row"><span class="od-label">Bank RRN / UTR</span><span class="od-value">${d.utr || 'Not Available'}</span></div>
                    </div>
                    <div class="od-section">
                        <div class="od-section-title"><i class="fas fa-link"></i> Additional Information</div>
                        ${openLink('Success URL', 'success')}
                        ${openLink('Failed URL', 'failed')}
                        ${openLink('Timeout URL', 'timeout')}
                    </div>
                `,
                showCancelButton: false,
                confirmButtonText: 'Close',
                buttonsStyling: false,
                customClass: { popup: 'swal-glass-popup', confirmButton: 'swal-glass-confirm' },
                background: 'transparent',
                backdrop: 'rgba(6,6,14,.65)'
            });
        });
    });

    // resolve a Pending order manually (Admin only - button only renders for Admin)
    window.changeOrderStatus = function(orderId) {
        let selected = null;
        const glass = {
            popup: 'swal-glass-popup',
            confirmButton: 'swal-glass-confirm',
            cancelButton: 'swal-glass-cancel',
            denyButton: 'swal-glass-deny'
        };
        Swal.fire({
            title: 'Change Payment Status',
            html: `<p style="color:rgba(255,255,255,.5);font-size:13px;margin-bottom:14px;">Order: <strong style="color:#fff">${orderId}</strong></p>
                   <div class="status-choice-wrap">
                       <div class="status-choice success-choice" data-val="SUCCESS"><i class="fas fa-check-circle"></i><span>Success</span></div>
                       <div class="status-choice failed-choice" data-val="FAILURE"><i class="fas fa-times-circle"></i><span>Failed</span></div>
                   </div>`,
            showCancelButton: true,
            confirmButtonText: 'Continue',
            cancelButtonText: 'Cancel',
            buttonsStyling: false,
            customClass: glass,
            background: 'transparent',
            backdrop: 'rgba(6,6,14,.65)',
            didOpen: () => {
                document.querySelectorAll('.status-choice').forEach(el => {
                    el.addEventListener('click', () => {
                        document.querySelectorAll('.status-choice').forEach(x => x.classList.remove('selected'));
                        el.classList.add('selected');
                        selected = el.dataset.val;
                    });
                });
            },
            preConfirm: () => {
                if (!selected) {
                    Swal.showValidationMessage('Please select a status');
                    return false;
                }
                return selected;
            }
        }).then(res => {
            if (!res.isConfirmed) return;
            const newStatus = res.value;
            Swal.fire({
                title: 'Are you sure?',
                text: `Mark this order as "${newStatus === 'SUCCESS' ? 'Success' : 'Failed'}"? This cannot be undone.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Confirm',
                cancelButtonText: 'Cancel',
                buttonsStyling: false,
                customClass: glass,
                background: 'transparent'
            }).then(confirmRes => {
                if (!confirmRes.isConfirmed) return;
                Swal.fire({ title: 'Updating...', allowOutsideClick: false, customClass: glass, background: 'transparent', didOpen: () => Swal.showLoading() });
                fetch('update_order_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'order_id=' + encodeURIComponent(orderId) + '&new_status=' + encodeURIComponent(newStatus)
                })
                .then(r => r.json())
                .then(data => {
                    if (data.status) {
                        Swal.fire({ icon: 'success', title: 'Updated', text: data.message, timer: 1500, showConfirmButton: false, customClass: glass, background: 'transparent' })
                            .then(() => window.location.reload());
                    } else {
                        Swal.fire({ icon: 'error', title: 'Failed', text: data.message, customClass: glass, background: 'transparent', buttonsStyling: false });
                    }
                })
                .catch(() => Swal.fire({ icon: 'error', title: 'Error', text: 'Something went wrong', customClass: glass, background: 'transparent', buttonsStyling: false }));
            });
        });
    };

    // refresh = simple reload, but with a spin on the icon for feedback
    $('#refreshBtn').on('click', function() {
        $(this).find('i').addClass('fa-spin');
        setTimeout(function() { window.location.reload(); }, 250);
    });

    // export currently-filtered rows to CSV client-side (no server round-trip needed)
    $('#exportCsv').on('click', function() {
        var csv = [['#','Mobile','Date Time','Merchant','Gateway Txn','Bank RRN','Order ID','Amount','Status']];
        table.rows({ search: 'applied' }).every(function() {
            var d = this.data();
            var cells = $(this.node()).find('td').map(function(){ return $(this).text().trim().replace(/\s+/g,' '); }).get();
            csv.push(cells);
        });
        var csvContent = csv.map(function(row) {
            return row.map(function(cell) { return '"' + String(cell).replace(/"/g, '""') + '"'; }).join(',');
        }).join('\n');
        var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'transactions_' + new Date().toISOString().slice(0,10) + '.csv';
        link.click();
        showToast('CSV exported');
    });
});
</script>
</body>
</html>
