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

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

$meterId = isset($_GET['meter_id']) ? (int)$_GET['meter_id'] : 0;

/* ===============================
GET METER
================================ */

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

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

/* ===============================
SAVE TENANT
================================ */

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

    $name  = trim($_POST['tenant_name']);
    $phone = trim($_POST['tenant_phone']);
    $email = trim($_POST['tenant_email']);

    if($name === ''){
        $error = "Tenant name is required.";
    } else {

        try {

            $pdo->beginTransaction();

            /* 1. CLOSE PREVIOUS TENANT */
            $stmt = $pdo->prepare("
            UPDATE meter_tenants
            SET active = 0, end_date = CURDATE()
            WHERE meter_id = ? AND active = 1
            ");
            $stmt->execute([$meterId]);

            /* 2. INSERT NEW TENANT */
            $stmt = $pdo->prepare("
            INSERT INTO meter_tenants 
            (meter_id, tenant_name, tenant_phone, tenant_email, start_date, active)
            VALUES (?,?,?,?,CURDATE(),1)
            ");
            $stmt->execute([$meterId, $name, $phone, $email]);

            $pdo->commit();

            $success = "Tenant assigned successfully.";

        } catch(Exception $e){
            $pdo->rollBack();
            $error = $e->getMessage();
        }

    }
}

?>

<div class="container">

<div class="page-header">
<h2>Assign Tenant</h2>
<p class="page-subtitle">
Meter: <?= htmlspecialchars($meter['meter_number']) ?> — <?= htmlspecialchars($meter['unit_name']) ?>
</p>
</div>

<?php if(isset($success)): ?>
<div style="background:#d4edda;padding:10px;border-radius:6px;margin-bottom:15px;">
<?= $success ?>
</div>
<?php endif; ?>

<?php if(isset($error)): ?>
<div style="background:#f8d7da;padding:10px;border-radius:6px;margin-bottom:15px;">
<?= $error ?>
</div>
<?php endif; ?>

<div class="stat-card">

<form method="POST">

<label>Tenant Name</label>
<input type="text" name="tenant_name" required>

<br><br>

<label>Phone</label>
<input type="text" name="tenant_phone">

<br><br>

<label>Email</label>
<input type="email" name="tenant_email">

<br><br>

<button class="btn btn-primary">Save Tenant</button>

</form>

</div>

</div>

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