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

// ----------------------
// Handle AJAX chart refresh
// ----------------------
if (isset($_GET['ajax']) && $_GET['ajax'] == 'chart') {

    $chart_res = mysqli_query($conn, "
        SELECT to_country, DATE(created_at) AS txn_date, SUM(send_amount) AS total
        FROM transactions
        GROUP BY to_country, DATE(created_at)
        ORDER BY txn_date ASC
    ");

    $chart_data = [];
    while ($row = mysqli_fetch_assoc($chart_res)) {
        $chart_data[$row['to_country']][] = [
            'date'  => $row['txn_date'],
            'total' => $row['total']
        ];
    }

    echo json_encode($chart_data);
    exit;
}

// ----------------------
// Pagination
// ----------------------
$limit  = 20;
$page   = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// ----------------------
// Filters
// ----------------------
$search    = $_GET['search'] ?? '';
$status    = $_GET['status'] ?? '';
$fromDate  = $_GET['from_date'] ?? '';
$toDate    = $_GET['to_date'] ?? '';
$toCountry = $_GET['to_country'] ?? '';

$where = [];

if ($search !== '') {
    $safe = mysqli_real_escape_string($conn, $search);
    $where[] = "(
        reference LIKE '%$safe%' OR
        sender_msisdn LIKE '%$safe%' OR
        receiver_msisdn LIKE '%$safe%'
    )";
}

if ($status !== '') {
    $safe = mysqli_real_escape_string($conn, $status);
    $where[] = "status = '$safe'";
}

if ($toCountry !== '') {
    $safe = mysqli_real_escape_string($conn, $toCountry);
    $where[] = "to_country = '$safe'";
}

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

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

// ----------------------
// Fetch transactions
// ----------------------
$trans_res = mysqli_query($conn, "
    SELECT *
    FROM transactions
    $whereSQL
    ORDER BY created_at DESC
    LIMIT $limit OFFSET $offset
");

// ----------------------
// Count total rows
// ----------------------
$total_res = mysqli_query($conn, "
    SELECT COUNT(*) AS cnt
    FROM transactions
    $whereSQL
");

$total_rows  = mysqli_fetch_assoc($total_res)['cnt'];
$total_pages = ceil($total_rows / $limit);

// ----------------------
// Fetch To-Country list
// ----------------------
$country_res = mysqli_query($conn, "
    SELECT DISTINCT to_country
    FROM transactions
    ORDER BY to_country ASC
");
?>
<!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"; ?>

<div class="container">

<div class="card">
<h2>Daily Transactions by Country</h2>
<div style="height:250px">
    <canvas id="countryChart"></canvas>
</div>
</div>

<div class="card">
<h2>Latest Transactions</h2>

<form method="GET" style="margin-bottom:15px;display:flex;gap:10px;flex-wrap:wrap;">
    <input type="text" name="search" placeholder="Search ref / sender / receiver"
           value="<?= htmlspecialchars($search) ?>">

    <select name="status">
        <option value="">All Status</option>
        <?php foreach(['INITIATED','QUEUED','SETTLED','FAILED'] as $s): ?>
            <option value="<?= $s ?>" <?= $status==$s?'selected':'' ?>><?= $s ?></option>
        <?php endforeach; ?>
    </select>

    <select name="to_country">
        <option value="">All To Countries</option>
        <?php while($c = mysqli_fetch_assoc($country_res)): ?>
            <option value="<?= $c['to_country'] ?>"
                <?= $toCountry==$c['to_country']?'selected':'' ?>>
                <?= $c['to_country'] ?>
            </option>
        <?php endwhile; ?>
    </select>

    <input type="date" name="from_date" value="<?= $fromDate ?>">
    <input type="date" name="to_date" value="<?= $toDate ?>">

    <button type="submit">Search</button>
</form>

<div class="table-responsive">
<table>
<thead>
<tr>
<th>Ref</th>
<th>Sender</th>
<th>Receiver</th>
<th>From</th>
<th>To</th>
<th>Send</th>
<th>Receive</th>
<th>Status</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<?php while($row = mysqli_fetch_assoc($trans_res)): ?>
<tr>
<td><?= $row['reference'] ?></td>
<td><?= $row['sender_msisdn'] ?></td>
<td><?= $row['receiver_msisdn'] ?></td>
<td><?= $row['from_country'] ?></td>
<td><?= $row['to_country'] ?></td>
<td><?= number_format($row['send_amount'],2) ?></td>
<td><?= number_format($row['receive_amount'],2) ?></td>
<td>
    <span class="status-label status-<?= $row['status'] ?>">
        <?= $row['status'] ?>
    </span>
</td>
<td><?= $row['created_at'] ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

<div class="pagination">
<?php
$query = $_GET;
for ($p=1; $p<=$total_pages; $p++):
    $query['page'] = $p;
?>
<a href="?<?= http_build_query($query) ?>"
   class="<?= $p==$page?'active':'' ?>">
   <?= $p ?>
</a>
<?php endfor; ?>
</div>

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