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

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

$success = "";

/* ===============================
ASSIGN CHARGE TO METER
================================ */

if($_SERVER['REQUEST_METHOD']=='POST'){

$meterId  = (int)$_POST['meter_id'];
$chargeId = (int)$_POST['charge_id'];

$stmt = $pdo->prepare("
INSERT INTO meter_charges (meter_id,charge_id)
VALUES (?,?)
");

$stmt->execute([$meterId,$chargeId]);

$success = "Charge assigned successfully.";

}

/* ===============================
LOAD METERS
================================ */

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


/* ===============================
LOAD CHARGES
================================ */

$charges = $pdo->query("
SELECT id,charge_name
FROM billing_charges
WHERE active=1
ORDER BY charge_name
")->fetchAll(PDO::FETCH_ASSOC);

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

<div class="main-content">

<h2>Assign Charge To Meter</h2>

<?php if($success): ?>

<div style="background:#ecfdf5;border:1px solid #16a34a;padding:10px;margin-bottom:20px;">
<?= $success ?>
</div>

<?php endif; ?>

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

<label>Meter</label>

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

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

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

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

<?php endforeach; ?>

</select>

<br><br>

<label>Charge</label>

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

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

<?php foreach($charges as $c): ?>

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

<?php endforeach; ?>

</select>

<br><br>

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

</form>

</div>

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