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

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

$meterId = isset($_GET['meter_id']) ? (int)$_GET['meter_id'] : 0;
$start   = $_GET['start'] ?? date('Y-m-01');
$end     = $_GET['end'] ?? date('Y-m-t');

$total = null;
$companyName = '';

if ($meterId > 0) {

    /* ===============================
       GET COMPANY NAME
    =============================== */

    $companyStmt = $pdo->prepare("
        SELECT c.company_name
        FROM companies c
        JOIN operational_meters m ON m.company_id = c.id
        WHERE m.id = ?
        LIMIT 1
    ");

    $companyStmt->execute([$meterId]);
    $companyRow = $companyStmt->fetch(PDO::FETCH_ASSOC);
    $companyName = $companyRow['company_name'] ?? 'EDM Solutions';


    /* ===============================
       GET TOTAL CONSUMPTION
    =============================== */

    $stmt = $pdo->prepare("
        SELECT SUM(daily_consumption) AS total_usage
        FROM meter_readings
        WHERE meter_id = ?
        AND reading_date BETWEEN ? AND ?
    ");

    $stmt->execute([$meterId, $start, $end]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $total = $result['total_usage'] ?? 0;


    /* ===============================
       GET TARIFF
    =============================== */

    $tariffStmt = $pdo->prepare("
        SELECT tariff_id
        FROM operational_meters
        WHERE id = ?
    ");

    $tariffStmt->execute([$meterId]);
    $meter = $tariffStmt->fetch(PDO::FETCH_ASSOC);

    if (!$meter || !$meter['tariff_id']) {
        die("No tariff assigned to this meter.");
    }

    $tariffId = (int)$meter['tariff_id'];


    /* ===============================
       CALCULATE BILL
    =============================== */

    $bill = calculateBlockBill($pdo, $tariffId, (float)$total);
    $totalAmount = $bill['total'];
    $breakdown = $bill['breakdown'];
}

?>

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

<div class="main-content">

<div class="breadcrumb" style="margin-bottom:15px;">
<a href="/core/public/dashboard.php">Dashboard</a> /
<a href="/core/public/modules/billing/">Billing</a> /
<span>Monthly Calculation</span>
</div>

<div class="page-header">
<h2>Monthly Usage Calculation</h2>
<div class="page-subtitle">
Consumption and tariff-based billing summary
</div>
</div>


<form method="GET" class="card-form">

<label>Select Operational Meter</label>

<select name="meter_id" required class="input">

<option value="">Select Meter</option>

<?php

$stmt = $pdo->query("
SELECT 
    om.id,
    om.meter_number,
    c.company_name
FROM operational_meters om
JOIN companies c ON c.id = om.company_id
WHERE om.status = 'ACTIVE'
ORDER BY om.meter_number ASC
");

while($m = $stmt->fetch(PDO::FETCH_ASSOC)){

$selected = ($meterId == $m['id']) ? 'selected' : '';

echo '<option value="'.$m['id'].'" '.$selected.'>
'.$m['meter_number'].' — '.$m['company_name'].'
</option>';

}

?>

</select>


<label>Start Date</label>
<input type="date" name="start" required value="<?= htmlspecialchars($start) ?>">

<label>End Date</label>
<input type="date" name="end" required value="<?= htmlspecialchars($end) ?>">

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

</form>


<?php if ($total !== null): ?>

<div class="stat-card" style="margin-top:30px;" id="invoice-area">

<div style="margin-bottom:25px;">
<h3 style="margin:0;">
<?= htmlspecialchars($companyName) ?>
</h3>

<div class="page-subtitle">
Billing Period: <?= htmlspecialchars($start) ?> to <?= htmlspecialchars($end) ?>
</div>
</div>


<div style="margin-bottom:20px;">
<div class="page-subtitle">Total Consumption</div>
<div class="number">
<?= number_format($total,4) ?> units
</div>
</div>


<div style="margin-bottom:25px;">
<div class="page-subtitle">Total Amount</div>
<div class="number" style="color:var(--edm-orange);">
R <?= number_format($totalAmount,2) ?>
</div>
</div>


<div class="table-wrap">

<table>

<thead>
<tr>
<th>Block</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 foreach ($breakdown as $row): ?>

<tr>
<td><?= htmlspecialchars($row['label']) ?></td>

<td style="text-align:right">
<?= number_format($row['units'],4) ?>
</td>

<td style="text-align:right">
R <?= number_format($row['rate'],2) ?>
</td>

<td style="text-align:right">
R <?= number_format($row['amount'],2) ?>
</td>
</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

</div>


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

<form method="POST" action="generate_invoice.php">

<input type="hidden" name="meter_id" value="<?= $meterId ?>">
<input type="hidden" name="start" value="<?= $start ?>">
<input type="hidden" name="end" value="<?= $end ?>">

<button type="submit" class="btn btn-primary">
Generate Invoice
</button>

</form>


<button onclick="printInvoice()" class="btn">
Print Invoice
</button>


<a href="export_pdf.php?meter_id=<?= $meterId ?>&start=<?= $start ?>&end=<?= $end ?>"
class="btn">
Export PDF
</a>

</div>

<?php endif; ?>

</div>


<script>

function printInvoice(){

var content = document.getElementById("invoice-area").innerHTML;

var win = window.open('', '', 'width=900,height=650');

win.document.write('<html><head><title>Invoice</title></head><body>');
win.document.write(content);
win.document.write('</body></html>');

win.document.close();
win.print();

}

</script>


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