<?php
require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../../config/database.php';

if (!isset($_GET['id'])) {
    die("Invoice ID missing.");
}

$invoiceId = (int)$_GET['id'];

/* LOAD INVOICE */
$stmt = $pdo->prepare("
SELECT i.*, cu.customer_name, ba.account_name
FROM invoices i
LEFT JOIN billing_accounts ba ON ba.id = i.billing_account_id
LEFT JOIN billing_customers cu ON cu.id = ba.customer_id
WHERE i.id = ?
LIMIT 1
");
$stmt->execute([$invoiceId]);
$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$invoice) die("Invoice not found.");

/* LOAD LINES */
$stmt = $pdo->prepare("
SELECT description, quantity, unit_price, total
FROM invoice_lines
WHERE invoice_id = ?
ORDER BY id ASC
");
$stmt->execute([$invoiceId]);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* READING FUNCTION */
function getMeterReadingsForPeriod(PDO $pdo, string $meterNumber, $start, $end)
{
    $stmt = $pdo->prepare("
        SELECT id FROM operational_meters
        WHERE meter_number = ?
        LIMIT 1
    ");
    $stmt->execute([$meterNumber]);
    $meterId = $stmt->fetchColumn();

    if (!$meterId) return null;

    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date < ?
        ORDER BY reading_date DESC, id DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $start]);
    $startReading = $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT reading_value
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date <= ?
        ORDER BY reading_date DESC, id DESC
        LIMIT 1
    ");
    $stmt->execute([$meterId, $end]);
    $endReading = $stmt->fetchColumn();

    if ($startReading === false || $endReading === false) {
        return null;
    }

    return [
        'previous' => (float)$startReading,
        'current'  => (float)$endReading,
        'usage'    => (float)$endReading - (float)$startReading
    ];
}

/* METERS */
$meters = [];
foreach ($items as $row) {
    if (strpos($row['description'], 'METER_HEADER::') === 0) {
        $meters[] = str_replace('METER_HEADER::', '', $row['description']);
    }
}
$meters = array_unique($meters);

$meterCount = count($meters);
$meterLabel = $meterCount === 1 ? 'Meter' : 'Meters';
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Invoice</title>

<style>
body { font-family: Arial, sans-serif; font-size: 12px; }
.header { margin-bottom: 20px; }

.table { width: 100%; border-collapse: collapse; }
.table th, .table td { border: 1px solid #ccc; padding: 6px; }
.table th { background: #f4f6f8; }

.right { text-align: right; }

.meter-header { background: #eee; font-weight: bold; }
.section-header { background: #f4f6f8; font-weight: bold; }
.usage-row { color: #555; font-size: 11px; }

.total-row { font-weight: bold; background: #fafafa; }
.account-total { font-weight: bold; background: #eef6ff; }

.total-box { margin-top: 20px; }
</style>

</head>

<body>

<div class="header">

<h2>Invoice #<?= htmlspecialchars($invoice['invoice_number']) ?></h2>

<div><strong>Customer:</strong> <?= htmlspecialchars($invoice['customer_name'] ?? '-') ?></div>
<div><strong>Account:</strong> <?= htmlspecialchars($invoice['account_name'] ?? '-') ?></div>

<div>
<strong>Unit:</strong> 
<?= htmlspecialchars($invoice['unit_name'] ?? '-') ?> 
(<?= $meterCount ?> <?= $meterLabel ?>)
</div>

<div><strong>Meters:</strong> <?= !empty($meters) ? implode(', ', $meters) : '-' ?></div>

<div><strong>Invoice Date:</strong> <?= htmlspecialchars($invoice['invoice_date']) ?></div>
<div><strong>Due Date:</strong> <?= htmlspecialchars($invoice['due_date']) ?></div>

<div>
<strong>Billing Period:</strong>
<?= htmlspecialchars($invoice['period_start']) ?> to <?= htmlspecialchars($invoice['period_end']) ?>
</div>

</div>

<table class="table">
<thead>
<tr>
<th>Description</th>
<th class="right">Units</th>
<th class="right">Rate</th>
<th class="right">Amount</th>
</tr>
</thead>

<tbody>

<?php
$currentMeter = '';
$meterTotal = 0;
$accountTotal = 0;
$sectionShown = false;

foreach ($items as $row):

$desc = $row['description'];

$isUnitCharge = false;
$isAccountCharge = false;

/* CHARGES */
if (strpos($desc, 'UNIT_CHARGE::') === 0) {
    if (!$sectionShown) {
        echo "<tr><td colspan='4' style='height:12px;'></td></tr>";
        echo "<tr class='section-header'><td colspan='4'>Unit & Account Charges</td></tr>";
        $sectionShown = true;
    }

    $desc = "Unit Charge: " . str_replace('UNIT_CHARGE::', '', $desc);
    $isUnitCharge = true;
    $accountTotal += (float)$row['total'];
}

elseif (strpos($desc, 'ACCOUNT_CHARGE::') === 0) {
    if (!$sectionShown) {
        echo "<tr><td colspan='4' style='height:12px;'></td></tr>";
        echo "<tr class='section-header'><td colspan='4'>Unit & Account Charges</td></tr>";
        $sectionShown = true;
    }

    $desc = "Account Charge: " . str_replace('ACCOUNT_CHARGE::', '', $desc);
    $isAccountCharge = true;
    $accountTotal += (float)$row['total'];
}

/* METER HEADER */
if (strpos($desc, 'METER_HEADER::') === 0):

    if ($currentMeter !== '') {
        echo "<tr><td colspan='4' style='height:8px;'></td></tr>";
        echo "<tr class='total-row'>
                <td colspan='3'>Meter Total</td>
                <td class='right'>R " . number_format($meterTotal,2) . "</td>
              </tr>";
    }

    $currentMeter = str_replace('METER_HEADER::', '', $desc);
    $meterTotal = 0;

    echo "<tr><td colspan='4' style='height:10px;'></td></tr>";

    echo "<tr class='meter-header'>
            <td colspan='4'>Meter: {$currentMeter}</td>
          </tr>";

    $readings = getMeterReadingsForPeriod(
        $pdo,
        $currentMeter,
        $invoice['period_start'],
        $invoice['period_end']
    );

    if ($readings) {
        echo "<tr class='usage-row'>
                <td colspan='4'>
                    Previous: {$readings['previous']} | Current: {$readings['current']} | Usage: {$readings['usage']}
                </td>
              </tr>";
    }

    continue;
endif;

/* CLOSE METER BEFORE UNIT */
if (($isUnitCharge || $isAccountCharge) && $currentMeter !== '') {
    echo "<tr><td colspan='4' style='height:8px;'></td></tr>";
    echo "<tr class='total-row'>
            <td colspan='3'>Meter Total</td>
            <td class='right'>R " . number_format($meterTotal,2) . "</td>
          </tr>";

    $currentMeter = '';
    $meterTotal = 0;
}
?>

<tr>
<td><?= htmlspecialchars($desc) ?></td>
<td class="right"><?= number_format((float)$row['quantity'],4) ?></td>
<td class="right">R <?= number_format((float)$row['unit_price'],2) ?></td>
<td class="right">R <?= number_format((float)$row['total'],2) ?></td>
</tr>

<?php
if (!$isUnitCharge && !$isAccountCharge) {
    $meterTotal += (float)$row['total'];
}

endforeach;
?>

<?php if ($currentMeter !== ''): ?>
<tr><td colspan="4" style="height:8px;"></td></tr>
<tr class="total-row">
<td colspan="3">Meter Total</td>
<td class="right">R <?= number_format($meterTotal,2) ?></td>
</tr>
<?php endif; ?>

<?php if ($accountTotal > 0): ?>
<tr><td colspan="4" style="height:10px;"></td></tr>
<tr class="account-total">
<td colspan="3">Unit & Account Charges Total</td>
<td class="right">R <?= number_format($accountTotal,2) ?></td>
</tr>
<?php endif; ?>

</tbody>
</table>

<div class="total-box">
<div>Subtotal: R <?= number_format((float)$invoice['subtotal'],2) ?></div>
<div>VAT: R <?= number_format((float)$invoice['vat_amount'],2) ?></div>
<h3>Total: R <?= number_format((float)$invoice['total'],2) ?></h3>
</div>

</body>
</html>