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

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

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

$meterId = $_GET['meter_id'] ?? 0;

if(!$meterId){
    die("Missing meter_id");
}

/* GET METER */
$stmt = $pdo->prepare("
SELECT id, meter_number, tariff_profile_id
FROM operational_meters
WHERE id = ?
");
$stmt->execute([$meterId]);
$meter = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

    $profileId = $_POST['tariff_profile_id'] ?? null;

    if(empty($profileId)){
        die("Select profile");
    }

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

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

    header("Location: meters.php?updated=1");
    exit;
}

/* LOAD PROFILES */
$profiles = $pdo->query("
SELECT p.id, p.profile_name, t.tariff_name
FROM tariff_profiles p
JOIN tariffs t ON p.tariff_id = t.id
ORDER BY t.tariff_name, p.profile_name
")->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">
<h2>Change Tariff Profile</h2>

<p><strong>Meter:</strong> <?= htmlspecialchars($meter['meter_number']) ?></p>

<form method="POST">

<label>Select Profile</label>
<select name="tariff_profile_id" required style="width:100%;padding:8px;">

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

<?php foreach($profiles as $p): ?>
<option value="<?= $p['id'] ?>" 
<?= $meter['tariff_profile_id']==$p['id'] ? 'selected' : '' ?>>
<?= htmlspecialchars($p['tariff_name']) ?> — <?= htmlspecialchars($p['profile_name']) ?>
</option>
<?php endforeach; ?>

</select>

<br><br>

<button class="btn btn-primary">Update Profile</button>

</form>

</div>

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