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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error'] = "Invalid request.";
    header("Location: meters.php");
    exit;
}

$meterId = (int)($_POST['meter_id'] ?? 0);
$action  = $_POST['action'] ?? '';
$userId  = $_SESSION['user_id'] ?? 0;
$reason  = trim($_POST['reason'] ?? '');

if (!$meterId || !$action) {
    $_SESSION['error'] = "Missing parameters.";
    header("Location: meters.php");
    exit;
}

try {

    $pdo->beginTransaction();

    /* Fetch current meter */
    $stmt = $pdo->prepare("
        SELECT status
        FROM operational_meters
        WHERE id = ?
        FOR UPDATE
    ");
    $stmt->execute([$meterId]);
    $meter = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$meter) {
        throw new Exception("Meter not found.");
    }

    $currentStatus = $meter['status'];
    $newStatus = null;

    /* ===============================
       Lifecycle Rules
    =============================== */

    switch ($action) {

        case 'suspend':
            if ($currentStatus === 'ACTIVE') {
                $newStatus = 'SUSPENDED';
            }
            break;

        case 'activate':
            if ($currentStatus === 'SUSPENDED') {
                $newStatus = 'ACTIVE';
            }
            break;

        case 'disconnect':
            if (in_array($currentStatus, ['ACTIVE', 'SUSPENDED'])) {
                $newStatus = 'DISCONNECTED';
            }
            break;
    }

    if (!$newStatus) {
        throw new Exception("Invalid status transition.");
    }

    /* Require reason for certain status changes */
    if (in_array($newStatus, ['SUSPENDED','DISCONNECTED']) && $reason === '') {
        throw new Exception("Reason is required for this status change.");
    }

    /* ===============================
       Update Operational Meter
    =============================== */

    $stmt = $pdo->prepare("
        UPDATE operational_meters
        SET status = ?
        WHERE id = ?
    ");
    $stmt->execute([$newStatus, $meterId]);

    /* ===============================
       Insert History Record
    =============================== */

    $stmt = $pdo->prepare("
        INSERT INTO operational_meter_status_history
        (operational_meter_id, old_status, new_status, reason, changed_by)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $meterId,
        $currentStatus,
        $newStatus,
        $reason,
        $userId
    ]);

    $pdo->commit();

    $_SESSION['success'] = "Status updated successfully.";

} catch (Exception $e) {

    $pdo->rollBack();
    $_SESSION['error'] = $e->getMessage();
}

header("Location: meter_view.php?id=" . $meterId);
exit;