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

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

$breadcrumb = "Meter Setup Wizard";

require_once __DIR__ . '/../../../includes/layout.php';

/* Load companies */
$companies = $pdo->query("SELECT id, company_name FROM companies ORDER BY company_name")->fetchAll(PDO::FETCH_ASSOC);

/* Load tariffs */
$tariffs = $pdo->query("SELECT id, tariff_name FROM tariffs ORDER BY tariff_name")->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="container">

<?php if(isset($_GET['saved'])): ?>
<div style="background:#e8f5e9;color:#2e7d32;padding:12px;border-radius:6px;margin-bottom:15px;">
Meter created successfully.
</div>
<?php endif; ?>

<div class="page-header">
<h2>Meter Setup</h2>
<p class="page-subtitle">Register meter, assign tariff and opening reading</p>
</div>

<div class="stat-card">

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

<label>Meter Number</label>
<input type="text" name="meter_number" required>

<label>Company</label>
<select name="company_id" required>
<option value="">Select Company</option>
<?php foreach($companies as $c): ?>
<option value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['company_name']) ?>
</option>
<?php endforeach; ?>
</select>

<label>Tariff</label>
<select name="tariff_id" required>
<option value="">Select Tariff</option>
<?php foreach($tariffs as $t): ?>
<option value="<?= $t['id'] ?>">
<?= htmlspecialchars($t['tariff_name']) ?>
</option>
<?php endforeach; ?>
</select>

<br>

<h4>Company Charges (Preview)</h4>

<div style="overflow-x:auto;margin-top:10px;">

<table style="width:100%;border-collapse:collapse;min-width:600px;">

<tr style="background:#f5f5f5;">
<th style="text-align:left;padding:8px;">Charge Name</th>
<th style="text-align:left;padding:8px;">Type</th>
<th style="text-align:left;padding:8px;">Value</th>
</tr>

<?php
$stmt = $pdo->query("
SELECT charge_name, charge_type, charge_value
FROM billing_charges
WHERE active = 1
ORDER BY apply_order ASC
");

$charges = $stmt->fetchAll(PDO::FETCH_ASSOC);

if(!$charges){
echo "<tr><td colspan='3' style='padding:8px;'>No active charges</td></tr>";
}

foreach($charges as $c){
echo "<tr>";
echo "<td style='padding:8px;'>".htmlspecialchars($c['charge_name'])."</td>";
echo "<td style='padding:8px;'>".$c['charge_type']."</td>";
echo "<td style='padding:8px;'>".$c['charge_value']."</td>";
echo "</tr>";
}
?>

</table>
</div>

<label>Opening Reading</label>
<input type="number" step="0.001" name="opening_reading">

<br><br>

<button class="btn btn-primary">Create Meter</button>

</form>

</div>

</div>

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