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

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

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

require_once __DIR__.'/../../includes/header.php';
require_once __DIR__.'/../../includes/sidebar.php';

/* ONLY load the block calculator */
require_once __DIR__.'/engine/calculate_block_bill.php';

$meters = $pdo->query("
SELECT id, meter_number
FROM operational_meters
WHERE status='ACTIVE'
ORDER BY meter_number
")->fetchAll(PDO::FETCH_ASSOC);

$result = null;

if(isset($_POST['simulate'])){

$meterId = (int)$_POST['meter_id'];
$newReading = (float)$_POST['reading'];

/* load meter tariff */

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

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

if(!$meter){
die("Meter not found");
}

/* previous reading */

$stmt = $pdo->prepare("
SELECT reading_value
FROM meter_readings
WHERE meter_id=?
ORDER BY id DESC
LIMIT 1
");

$stmt->execute([$meterId]);
$prev = $stmt->fetchColumn();

$prev = $prev ? (float)$prev : 0;

$consumption = $newReading - $prev;

if($consumption < 0){
die("Reading lower than previous");
}

/* run tariff calculation */

$result = calculateBlockBill($pdo,$meter['tariff_id'],$consumption);

}
?>

<div class="main-content">

<div class="page-header">
<h2>Billing Simulator</h2>
</div>

<div class="stat-card">

<form method="POST">

<div class="form-row">

<div class="form-group">
<label>Select Meter</label>

<select name="meter_id" required>
<option value="">Select Meter</option>

<?php foreach($meters as $m): ?>

<option value="<?= $m['id'] ?>">
<?= htmlspecialchars($m['meter_number']) ?>
</option>

<?php endforeach; ?>

</select>

</div>

<div class="form-group">

<label>New Reading</label>

<input type="number" step="0.001" name="reading" required>

</div>

</div>

<div class="form-actions">

<button name="simulate" class="btn btn-primary">
Simulate Billing
</button>

</div>

</form>

</div>

<?php if($result): ?>

<div class="stat-card">

<h3>Billing Breakdown</h3>

<table class="table">

<thead>
<tr>
<th>Item</th>
<th>Units</th>
<th>Rate</th>
<th>Amount</th>
</tr>
</thead>

<tbody>

<?php foreach($result['breakdown'] as $row): ?>

<tr>

<td><?= htmlspecialchars($row['label']) ?></td>
<td><?= $row['units'] ?></td>
<td>R <?= number_format($row['rate'],2) ?></td>
<td>R <?= number_format($row['amount'],2) ?></td>

</tr>

<?php endforeach; ?>

<tr>

<td colspan="3"><b>Total</b></td>
<td><b>R <?= number_format($result['total'],2) ?></b></td>

</tr>

</tbody>

</table>

</div>

<?php endif; ?>

</div>

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