<?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);

/* PAYMENTS */
$stmt = $pdo->prepare("
SELECT *
FROM invoice_payments
WHERE invoice_id = ?
ORDER BY payment_date ASC, id ASC
");
$stmt->execute([$invoiceId]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalPaid = 0;
foreach ($payments as $p) {
    $totalPaid += (float)$p['amount'];
}

$balance = (float)$invoice['total'] - $totalPaid;

/* FIXED 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';
?>

<?php require_once __DIR__ . '/../../../includes/header.php'; ?>
<?php require_once __DIR__ . '/../../../includes/sidebar.php'; ?>

<div class="main-content">

<?php if(isset($_GET['error']) && $_GET['error'] == 'has_payments'): ?>
<div style="
    background:#fff3cd;
    border:1px solid #ffeeba;
    color:#856404;
    padding:12px;
    border-radius:8px;
    margin-bottom:15px;
    font-weight:500;
">
    ⚠️ Cannot regenerate this invoice because payments exist.
    Please reverse or remove payments first.
</div>
<?php endif; ?>

<?php if(isset($_GET['success']) && $_GET['success'] == 'payment_reversed'): ?>
<div style="
    background:#d4edda;
    border:1px solid #c3e6cb;
    color:#155724;
    padding:12px;
    border-radius:8px;
    margin-bottom:15px;
    font-weight:500;
">
    ✅ Payment reversed successfully.
</div>
<?php endif; ?>

<?php if(isset($_GET['regen']) && $_GET['regen'] == 'success'): ?>
<div style="
    background:#d1ecf1;
    border:1px solid #bee5eb;
    color:#0c5460;
    padding:12px;
    border-radius:8px;
    margin-bottom:15px;
    font-weight:500;
">
    ✅ Invoice regenerated successfully.
</div>
<?php endif; ?>

<?php if(isset($_GET['error']) && $_GET['error'] == 'no_lines'): ?>
<div style="
    background:#f8d7da;
    border:1px solid #f5c6cb;
    color:#721c24;
    padding:12px;
    border-radius:8px;
    margin-bottom:15px;
    font-weight:500;
">
    ⚠️ Regeneration failed. No billing lines could be created for this invoice.
    Please check meter readings or tariff configuration.
</div>
<?php endif; ?>

<div class="page-header">
    <h2>Invoice #<?= htmlspecialchars($invoice['invoice_number']) ?></h2>

    <div style="margin:15px 0; display:flex; gap:10px; flex-wrap:wrap;">

        <a href="invoice_pdf.php?id=<?= $invoiceId ?>" target="_blank"
           style="padding:8px 14px;background:#3498db;color:#fff;text-decoration:none;border-radius:4px;">
            Download PDF
        </a>

        <a href="add_payment.php?invoice_id=<?= $invoiceId ?>"
           style="padding:8px 14px;background:#27ae60;color:#fff;text-decoration:none;border-radius:4px;">
            Add Payment
        </a>

        <a href="../regenerate_invoice.php?id=<?= $invoiceId ?>"
           onclick="return confirm('Are you sure you want to regenerate this invoice?')"
           style="padding:8px 14px;background:#e67e22;color:#fff;text-decoration:none;border-radius:4px;">
            Regenerate
        </a>

    </div>
</div>

<div class="stat-card" id="invoice-area">

    <div style="margin-bottom:20px;">
        <h3><?= htmlspecialchars($invoice['customer_name'] ?? '-') ?></h3>

        <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>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Charge</th>
                    <th style="text-align:right;">Units</th>
                    <th style="text-align:right;">Rate</th>
                    <th style="text-align:right;">Amount</th>
                </tr>
            </thead>

            <tbody>
            <?php
            $currentMeter = '';
            $meterTotal = 0;

            foreach ($items as $row):

                $desc = $row['description'];

                $isCharge = false;
                $isMeterCharge = false;
                $isUnitCharge = false;
                $isAccountCharge = false;

                if (strpos($desc, 'METER_CHARGE::') === 0) {
                    $parts = explode('::', $desc);
                    $desc = $parts[2] . " (Meter " . $parts[1] . ")";
                    $isMeterCharge = true;
                    $isCharge = true;
                }
                elseif (strpos($desc, 'UNIT_CHARGE::') === 0) {
                    $desc = "Unit Charge: " . str_replace('UNIT_CHARGE::', '', $desc);
                    $isUnitCharge = true;
                    $isCharge = true;
                }
                elseif (strpos($desc, 'ACCOUNT_CHARGE::') === 0) {
                    $desc = "Account Charge: " . str_replace('ACCOUNT_CHARGE::', '', $desc);
                    $isAccountCharge = true;
                    $isCharge = true;
                }
                elseif (strpos($desc, 'CHARGE::') === 0) {
                    $desc = str_replace('CHARGE::', '', $desc);
                    $isCharge = true;
                }

                if (strpos($desc, 'METER_HEADER::') === 0):

                    if ($currentMeter !== '') {
                        echo "<tr style='font-weight:bold;background:#fafafa;'>
                                <td colspan='3'>Meter Total</td>
                                <td style='text-align:right;'>R " . number_format($meterTotal,2) . "</td>
                              </tr>";
                    }

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

                    echo "<tr style='background:#f4f6f8;font-weight:bold;'>
                            <td colspan='4'>Meter: {$currentMeter}</td>
                          </tr>";

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

                    if ($readings) {
                        echo "<tr>
                                <td colspan='4' style='color:#555;padding:8px 10px;'>
                                    Previous: {$readings['previous']} | Current: {$readings['current']} | Usage: {$readings['usage']}
                                </td>
                              </tr>";
                    }

                    continue;
                endif;
            ?>

            <?php
            if (($isUnitCharge || $isAccountCharge) && $currentMeter !== '') {
    echo "<tr style='font-weight:bold;background:#fafafa;'>
            <td colspan='3'>Meter Total</td>
            <td style='text-align:right;'>R " . number_format($meterTotal,2) . "</td>
          </tr>";

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

if ($isUnitCharge || $isAccountCharge) {
    echo "<tr><td colspan='4' style='padding-top:15px;'></td></tr>";
}
            ?>

            <tr style="<?=
                $isAccountCharge ? 'color:#c0392b;font-weight:bold;' :
                ($isUnitCharge ? 'color:#8e44ad;font-style:italic;' :
                ($isMeterCharge ? 'color:#555;font-style:italic;' : ''))
            ?>">
                <td><?= htmlspecialchars($desc) ?></td>
                <td style="text-align:right;"><?= number_format((float)$row['quantity'],4) ?></td>
                <td style="text-align:right;">R <?= number_format((float)$row['unit_price'],2) ?></td>
                <td style="text-align:right;">R <?= number_format((float)$row['total'],2) ?></td>
            </tr>

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

            endforeach;
            ?>

            <?php
            if ($currentMeter !== '') {
                echo "<tr style='font-weight:bold;background:#fafafa;'>
                        <td colspan='3'>Meter Total</td>
                        <td style='text-align:right;'>R " . number_format($meterTotal,2) . "</td>
                      </tr>";
            }
            ?>
            </tbody>
        </table>
    </div>

    <div style="margin-top:20px;">
        <div><strong>Subtotal:</strong> R <?= number_format((float)$invoice['subtotal'],2) ?></div>
        <div><strong>VAT:</strong> R <?= number_format((float)$invoice['vat_amount'],2) ?></div>
        <div><strong>Total Paid:</strong> R <?= number_format($totalPaid,2) ?></div>
        <div><strong>Balance:</strong> R <?= number_format($balance,2) ?></div>
        <h3 style="color:#f2531e;">Total: R <?= number_format((float)$invoice['total'],2) ?></h3>
    </div>

</div>

<?php if(!empty($payments)): ?>
<div class="stat-card" style="margin-top:20px;">

    <h3>Payments</h3>

    <table width="100%">
        <tr>
            <th>Date</th>
            <th>Amount</th>
            <th>Method</th>
            <th>Action</th>
        </tr>

        <?php foreach($payments as $p): ?>
        <tr>
            <td><?= htmlspecialchars($p['payment_date']) ?></td>
            <td>R <?= number_format((float)$p['amount'],2) ?></td>
            <td><?= htmlspecialchars($p['payment_method'] ?? '-') ?></td>
            <td>
                <a href="reverse_payment.php?payment_id=<?= $p['id'] ?>"
                   style="color:red;"
                   onclick="return confirm('Reverse this payment?')">
                   Reverse
                </a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>

</div>
<?php endif; ?>

</div>

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