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

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

$user_id    = $_SESSION['user_id'] ?? 0;
$company_id = $_SESSION['company_id'] ?? null;
$role       = $_SESSION['role_name'] ?? '';

$success = "";

/* ==========================================
ASSIGN TARIFF
========================================== */

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

$meterId  = (int)$_POST['meter_id'];
$tariffId = (int)$_POST['tariff_id'];

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

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

$success = "Tariff assigned successfully.";

}


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

if ($role === 'SUPER_ADMIN') {

$stmt = $pdo->query("
SELECT om.id,
       om.meter_number,
       om.status,
       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
");

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

} else {

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

$stmt->execute([$company_id]);
$meters = $stmt->fetchAll(PDO::FETCH_ASSOC);

}


/* ==========================================
LOAD TARIFFS
========================================== */

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


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

<div class="main-content">

<h2>Assign Tariff 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>Operational Meter</label>

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

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

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

<option value="<?= $m['id'] ?>">

<?= htmlspecialchars($m['meter_number']) ?>

<?php if($m['company_name']): ?>
 — <?= htmlspecialchars($m['company_name']) ?>
<?php endif; ?>

</option>

<?php endforeach; ?>

</select>


<br><br>


<label>Tariff</label>

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

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

<?php foreach($tariffs as $t): ?>

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

<?php endforeach; ?>

</select>


<br><br>


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


</form>

</div>

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