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

require_once $_SERVER['DOCUMENT_ROOT'].'/core/includes/auth.php';
requireLogin();
requirePermission('view_reports');

require_once $_SERVER['DOCUMENT_ROOT'].'/core/config/database.php';

/* ===============================
INPUT
================================ */
$invoiceId = $_GET['invoice_id'] ?? 0;
$fromDate  = $_GET['from_date'] ?? '';
$toDate    = $_GET['to_date'] ?? '';
$exportPdf = isset($_GET['export_pdf']);

if(!$invoiceId){
    die("Missing invoice_id");
}

/* ===============================
CALL API
================================ */
ob_start();
$_GET['invoice_id'] = $invoiceId;
require $_SERVER['DOCUMENT_ROOT'].'/api/reports/get.php';
$response = ob_get_clean();

$data = json_decode($response, true);

if(!$data || $data['status'] !== 'success'){
    die("Invalid API response");
}

$rows = $data['data'] ?? [];

/* ===============================
LOAD METERS
================================ */
$stmt = $pdo->query("SELECT meter_number, unit_name FROM operational_meters");
$meterMap = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

/* ===============================
GROUP BY UNIT
================================ */
$grouped = [];

foreach($rows as $row){

    // DATE FILTER (optional)
    if($fromDate || $toDate){
        $date = date('Y-m-d'); // fallback (API doesn't give date)
        if($fromDate && $date < $fromDate) continue;
        if($toDate && $date > $toDate) continue;
    }

    $unit = $meterMap[$row['meter_number']] ?? $row['meter_number'];
    $grouped[$unit][] = $row;
}

/* ===============================
TOTALS
================================ */
$totalUsage = 0;
$totalAmount = 0;

/* ===============================
PDF MODE
================================ */
if($exportPdf){
    echo "<html><head><title>Report</title></head><body>";
    echo "<h2>Meter Transaction Report</h2>";
    echo "<p>Invoice ID: {$invoiceId}</p>";
}
else{
    require_once $_SERVER['DOCUMENT_ROOT'].'/core/includes/header.php';
    require_once $_SERVER['DOCUMENT_ROOT'].'/core/includes/sidebar.php';
}
?>

<div class="main-content">

    <div class="page-header">
        <h1>Meter Transaction Report</h1>
        <p>Invoice ID: <?= htmlspecialchars($invoiceId) ?></p>
    </div>

    <!-- FILTER -->
    <?php if(!$exportPdf): ?>
    <form method="GET" style="margin-bottom:15px; display:flex; gap:10px;">
        <input type="hidden" name="invoice_id" value="<?= $invoiceId ?>">

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

        <button class="btn btn-primary">Filter</button>

        <a href="?invoice_id=<?= $invoiceId ?>&export_pdf=1" class="btn btn-success">
            Export PDF
        </a>
    </form>
    <?php endif; ?>

    <?php foreach($grouped as $unit => $meters): ?>

        <?php
        $unitTotal = 0;
        $unitUsage = 0;
        ?>

        <div class="card">

            <div class="card-header">
                <strong>Unit:</strong> <?= htmlspecialchars($unit) ?>
            </div>

            <div class="card-body">

                <table border="1" cellpadding="6" width="100%">

                    <thead>
                        <tr>
                            <th>Meter</th>
                            <th>Type</th>
                            <th>Previous</th>
                            <th>Current</th>
                            <th>Usage</th>
                            <th>Usage Charge</th>
                            <th>Meter Fees</th>
                            <th>Total</th>
                        </tr>
                    </thead>

                    <tbody>

                        <?php foreach($meters as $row):

                            $usage = (float)$row['usage'];
                            $amount = (float)$row['total'];

                            $totalUsage += $usage;
                            $totalAmount += $amount;

                            $unitUsage += $usage;
                            $unitTotal += $amount;
                        ?>

                        <tr>
                            <td>
                                <a href="meter_details.php?meter=<?= urlencode($row['meter_number']) ?>">
                                    <?= htmlspecialchars($row['meter_number']) ?>
                                </a>
                            </td>
                            <td><?= htmlspecialchars($row['meter_type']) ?></td>
                            <td><?= number_format($row['previous'],2) ?></td>
                            <td><?= number_format($row['current'],2) ?></td>
                            <td><?= number_format($usage,2) ?></td>
                            <td>R<?= number_format($row['usage_charge'],2) ?></td>
                            <td>R<?= number_format($row['meter_fees'],2) ?></td>
                            <td><strong>R<?= number_format($amount,2) ?></strong></td>
                        </tr>

                        <?php endforeach; ?>

                    </tbody>

                </table>

                <div style="text-align:right; margin-top:10px;">
                    <strong>Unit Usage:</strong> <?= number_format($unitUsage,2) ?> |
                    <strong>Unit Total:</strong> R<?= number_format($unitTotal,2) ?>
                </div>

            </div>

        </div>

    <?php endforeach; ?>

    <!-- GRAND TOTAL -->
    <div class="card" style="margin-top:20px;">
        <div class="card-body">
            <strong>Total Usage:</strong> <?= number_format($totalUsage,2) ?><br>
            <strong>Total Amount:</strong> R<?= number_format($totalAmount,2) ?>
        </div>
    </div>

</div>

<?php
if($exportPdf){
    echo "<script>window.print();</script></body></html>";
}else{
    require_once $_SERVER['DOCUMENT_ROOT'].'/core/includes/layout_footer.php';
}
?>