<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
requirePermission('view_reports');

require_once __DIR__.'/../../../includes/layout.php';

/* ===============================
INPUT
================================ */
$accountId = $_GET['account_id'] ?? '';

/* ===============================
CALL API
================================ */
ob_start();

$_GET['account_id'] = $accountId;

require __DIR__.'/../../../../api/reports/aging.php';

$response = ob_get_clean();
$data = json_decode($response, true);

if(!$data || $data['status'] !== 'success'){
    die("Failed to load aging report");
}

$buckets = $data['data']['buckets'];
$total = $data['data']['total_outstanding'];
?>

<!-- ✅ Chart.js (PLACED CORRECTLY IN HTML, NOT PHP) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div class="container">
<h2>Aging Report</h2>

<!-- FILTER -->
<form method="GET" style="margin-bottom:15px; display:flex; gap:10px; align-items:end;">

    <div>
        <label>Account ID (optional)</label><br>
        <input type="number" name="account_id" value="<?= htmlspecialchars($accountId) ?>" class="form-control">
    </div>

    <div>
        <button type="submit" class="btn btn-primary">Filter</button>
    </div>

    <div>
        <a href="aging.php" class="btn btn-secondary">Reset</a>
    </div>

</form>

<!-- SUMMARY CARDS (CLICKABLE 🔥) -->
<div style="display:flex; gap:15px; margin-bottom:20px; flex-wrap:wrap;">

    <a href="aging_details.php?bucket=0_30" class="card" style="padding:15px; min-width:150px; text-decoration:none;">
        <strong>0–30 Days</strong>
        <h3 style="color:#27ae60;">R <?= number_format($buckets['0_30'],2) ?></h3>
    </a>

    <a href="aging_details.php?bucket=31_60" class="card" style="padding:15px; min-width:150px; text-decoration:none;">
        <strong>31–60 Days</strong>
        <h3 style="color:#f39c12;">R <?= number_format($buckets['31_60'],2) ?></h3>
    </a>

    <a href="aging_details.php?bucket=61_90" class="card" style="padding:15px; min-width:150px; text-decoration:none;">
        <strong>61–90 Days</strong>
        <h3 style="color:#e67e22;">R <?= number_format($buckets['61_90'],2) ?></h3>
    </a>

    <a href="aging_details.php?bucket=90_plus" class="card" style="padding:15px; min-width:150px; text-decoration:none;">
        <strong>90+ Days</strong>
        <h3 style="color:#e74c3c;">R <?= number_format($buckets['90_plus'],2) ?></h3>
    </a>

</div>

<!-- ✅ CHART -->
<canvas id="agingChart" height="100" style="margin-bottom:20px;"></canvas>

<!-- TOTAL -->
<div class="card" style="padding:20px; margin-bottom:20px;">
    <h3>Total Outstanding</h3>
    <h1 style="color:#c0392b;">
        R <?= number_format($total,2) ?>
    </h1>
</div>

<!-- TABLE VIEW -->
<table class="table table-bordered">
<thead>
<tr>
    <th>Bucket</th>
    <th>Amount</th>
</tr>
</thead>

<tbody>
<tr>
    <td>0–30 Days</td>
    <td>R <?= number_format($buckets['0_30'],2) ?></td>
</tr>

<tr>
    <td>31–60 Days</td>
    <td>R <?= number_format($buckets['31_60'],2) ?></td>
</tr>

<tr>
    <td>61–90 Days</td>
    <td>R <?= number_format($buckets['61_90'],2) ?></td>
</tr>

<tr>
    <td>90+ Days</td>
    <td>R <?= number_format($buckets['90_plus'],2) ?></td>
</tr>

</tbody>
</table>

</div>

<!-- ✅ CHART SCRIPT (BOTTOM - VERY IMPORTANT) -->
<script>
document.addEventListener("DOMContentLoaded", function () {

    const ctx = document.getElementById('agingChart');

    if (!ctx) return;

    new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ['0-30', '31-60', '61-90', '90+'],
            datasets: [{
                data: [
                    <?= (float)$buckets['0_30'] ?>,
                    <?= (float)$buckets['31_60'] ?>,
                    <?= (float)$buckets['61_90'] ?>,
                    <?= (float)$buckets['90_plus'] ?>
                ],
                backgroundColor: [
                    '#27ae60',
                    '#f39c12',
                    '#e67e22',
                    '#e74c3c'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

});
</script>

<?php require_once __DIR__.'/../../../includes/layout_footer.php'; ?>