<?php
// country_transaction_list.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

include "includes/db_connect.php";
include "includes/auth.php";
checkAdmin();



// ----------------------
// Read Filters from GET
// ----------------------
// ----------------------
// Read Filters from GET
// ----------------------
$country  = isset($_GET['to_country']) ? mysqli_real_escape_string($conn, $_GET['to_country']) : '';
$status   = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$fromDate = isset($_GET['from_date']) ? mysqli_real_escape_string($conn, $_GET['from_date']) : '';
$toDate   = isset($_GET['to_date']) ? mysqli_real_escape_string($conn, $_GET['to_date']) : '';


// echo "<pre>";
// print_r($_GET);
// echo "</pre>";
// exit;


// ----------------------
// Build WHERE clause
// ----------------------
$where = [];

if ($country !== '') {
    $where[] = "to_country = '$country'";
}

if ($status !== '') {
    $where[] = "status = '$status'";
}

if ($fromDate !== '' && $toDate !== '') {
    $where[] = "DATE(created_at) BETWEEN '$fromDate' AND '$toDate'";
}

$whereSQL = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// ----------------------
// Summary Totals
// ----------------------
$summarySQL = "
    SELECT 
        COUNT(*) as total_count,
        SUM(send_amount) as total_send,
        SUM(receive_amount) as total_receive
    FROM transactions
    $whereSQL
";
$summaryResult = mysqli_query($conn, $summarySQL);
$summary = mysqli_fetch_assoc($summaryResult);


// ----------------------
// Pagination
// ----------------------
$limit = 50;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;

$offset = ($page - 1) * $limit;

// Count total rows
$countSQL = "SELECT COUNT(*) as total_rows FROM transactions $whereSQL";
$countResult = mysqli_query($conn, $countSQL);
$countRow = mysqli_fetch_assoc($countResult);
$totalRows = $countRow['total_rows'];
$totalPages = ceil($totalRows / $limit);






// ----------------------
// Fetch Transactions
// ----------------------
$sql = "
    SELECT 
        reference,
        send_amount,
        receive_amount,
        status,
        from_country,
        to_country,
        sender_msisdn,
        receiver_msisdn,
        created_at
    FROM transactions
    $whereSQL
    ORDER BY created_at DESC
    LIMIT $limit OFFSET $offset
";

// echo $sql;
// exit;


// ----------------------
// CSV Export
// ----------------------
if (isset($_GET['export']) && $_GET['export'] == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="transactions_'.$country.'.csv"');

    $output = fopen("php://output", "w");
    fputcsv($output, ['Reference','Sender','Receiver','From','To','Send Amount','Receive Amount','Status','Date']);

    $exportQuery = mysqli_query($conn, "
        SELECT reference, sender_msisdn, receiver_msisdn,
               from_country, to_country, send_amount,
               receive_amount, status, created_at
        FROM transactions
        $whereSQL
    ");

    while ($row = mysqli_fetch_assoc($exportQuery)) {
        fputcsv($output, $row);
    }

    fclose($output);
    exit;
}


$result = mysqli_query($conn, $sql);

// Helper to rebuild query params for back link
function backLinkParams() {
    $params = [];
    if (!empty($_GET['to_country'])) $params['to_country'] = $_GET['to_country'];
    if (!empty($_GET['from_date'])) $params['from_date'] = $_GET['from_date'];
    if (!empty($_GET['to_date'])) $params['to_date'] = $_GET['to_date'];
    return http_build_query($params);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Regulatory Dashboard - Mobex ADR Admin</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
body { font-family:'Inter',sans-serif; background:#f0f4f8; margin:0; }
.container { max-width:1000px; margin:auto; padding:20px; }
.card { background:#fff; padding:20px; border-radius:12px;
        box-shadow:0 10px 20px rgba(0,0,0,0.05); margin-bottom:20px; }
h2 { margin-bottom:15px; color:#1f2937; }
.table-responsive { overflow-x:auto; }
table { width:100%; border-collapse:collapse; }
th, td { padding:10px 8px; font-size:0.85rem; }
thead { background:#f3f4f6; }
tr:hover { background:#f9fafb; }
.status-label { font-weight:600; padding:3px 6px; border-radius:6px; color:#fff; font-size:0.75rem; }
.status-INITIATED { background:#f59e0b; }
.status-QUEUED { background:#3b82f6; }
.status-SETTLED { background:#10b981; }
.status-FAILED { background:#ef4444; }
.pagination { display:flex; justify-content:center; gap:5px; margin-top:10px; flex-wrap:wrap; }
.pagination a { padding:5px 10px; background:#6366f1; color:#fff;
                border-radius:6px; text-decoration:none; }
.pagination a.active { background:#4f46e5; font-weight:600; }
input, select { padding:6px 8px; border-radius:6px; border:1px solid #d1d5db; }
button { background:#6366f1; color:#fff; border:none;
         padding:6px 12px; border-radius:6px; cursor:pointer; }
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let chartData = {}, labels = [], chart;

function fetchChart(){
    fetch('transactions.php?ajax=chart')
    .then(r=>r.json())
    .then(data=>{
        chartData = data;
        labels = [...new Set([].concat(...Object.values(chartData).map(a=>a.map(d=>d.date))))];
        renderChart();
    });
}

function renderChart(){
    let ctx = document.getElementById('countryChart');
    if(chart) chart.destroy();

    chart = new Chart(ctx,{
        type:'bar',
        data:{
            labels:labels,
            datasets:Object.keys(chartData).map(c=>{
                let totals = labels.map(d=>{
                    let f = chartData[c].find(e=>e.date===d);
                    return f ? f.total : 0;
                });
                let col = '#'+Math.floor(Math.random()*16777215).toString(16);
                return {label:c,data:totals,backgroundColor:col};
            })
        },
        options:{responsive:true, scales:{y:{beginAtZero:true}}}
    });
}

window.onload = ()=>{ fetchChart(); setInterval(fetchChart,10000); };
</script>
</head>

<body>
<?php include "includes/mobex_sidebar.php"; ?>

<h2>
Transactions
<?= $country ? " for " . htmlspecialchars($country) : "" ?>
<?= $status ? " - " . htmlspecialchars($status) : "" ?>
</h2>

<div style="margin-bottom:15px;">
    <a href="?to_country=<?= urlencode($country) ?>">All</a> |
    <a href="?to_country=<?= urlencode($country) ?>&status=SETTLED">Settled</a> |
    <a href="?to_country=<?= urlencode($country) ?>&status=FAILED">Failed</a> |
    <a href="?to_country=<?= urlencode($country) ?>&status=QUEUED">Queued</a> |
    <a href="?to_country=<?= urlencode($country) ?>&export=csv">⬇ Export CSV</a>
</div>


<div class="filters">
    <?php if ($fromDate && $toDate): ?>
        Date: <?= htmlspecialchars($fromDate) ?> → <?= htmlspecialchars($toDate) ?>
    <?php endif; ?>
</div>

<div class="card" style="margin-bottom:15px;">
    <strong>Total Transactions:</strong> <?= number_format($summary['total_count'] ?? 0) ?><br>
    <strong>Total Send Amount:</strong> <?= number_format($summary['total_send'] ?? 0, 2) ?><br>
    <strong>Total Receive Amount:</strong> <?= number_format($summary['total_receive'] ?? 0, 2) ?>
</div>

<div class="card table-responsive">

<table>
    <thead>
    <tr>
        <th>Reference</th>
        <th>Sender</th>
        <th>Receiver</th>
        <th>From</th>
        <th>To</th>
        <th>Send Amount</th>
        <th>Receive Amount</th>
        <th>Status</th>
        <th>Date</th>
    </tr>
    </thead>
    <tbody>
    <?php if(mysqli_num_rows($result) > 0): ?>
        <?php while ($row = mysqli_fetch_assoc($result)) { ?>
            <tr>
                <td><?= htmlspecialchars($row['reference']) ?></td>
                <td><?= htmlspecialchars($row['sender_msisdn']) ?></td>
                <td><?= htmlspecialchars($row['receiver_msisdn']) ?></td>
                <td><?= htmlspecialchars($row['from_country']) ?></td>
                <td><?= htmlspecialchars($row['to_country']) ?></td>
                <td><?= number_format($row['send_amount'], 2) ?></td>
                <td><?= number_format($row['receive_amount'], 2) ?></td>
                <td><?= htmlspecialchars($row['status']) ?></td>
                <td><?= htmlspecialchars($row['created_at']) ?></td>
            </tr>
        <?php } ?>
    <?php else: ?>
        <tr><td colspan="9" style="text-align:center;">No transactions found for the selected filters</td></tr>
    <?php endif; ?>
    </tbody>
    <div style="margin-top:20px;">
<?php if ($totalPages > 1): ?>
    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <a href="?to_country=<?= urlencode($country) ?>&status=<?= urlencode($status) ?>&page=<?= $i ?>">
            <?= $i ?>
        </a>
    <?php endfor; ?>
<?php endif; ?>
</div>
</table>

</div>
</body>
</html>
