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

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

$message = "";
$error = "";

/* =====================================================
   HANDLE FORM
===================================================== */

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

    $meter_number = trim($_POST['meter_number']);
    $reason       = trim($_POST['reason']);

    if (empty($meter_number) || empty($reason)) {
        $error = "All fields are required.";
    } else {

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

        if (!$meter) {
            $error = "Meter not found.";
        } elseif ($meter['status'] !== 'INSTALLED') {
            $error = "Only INSTALLED meters can be replaced.";
        } else {

            // Prevent duplicate pending
            $check = $pdo->prepare("
                SELECT id FROM replacement_requests
                WHERE old_meter_id = ?
                AND status = 'PENDING'
            ");
            $check->execute([$meter['id']]);

            if ($check->rowCount() > 0) {
                $error = "A pending replacement already exists.";
            } else {

                $pdo->beginTransaction();

                try {

                    // Insert replacement request
                    $insert = $pdo->prepare("
                        INSERT INTO replacement_requests
                        (old_meter_id, requested_by_user_id, reason, status, created_at)
                        VALUES (?, ?, ?, 'PENDING', NOW())
                    ");

                    $insert->execute([
                        $meter['id'],
                        $_SESSION['user_id'],
                        $reason
                    ]);

                    // Audit log
                    $audit = $pdo->prepare("
                        INSERT INTO audit_logs (user_id, action)
                        VALUES (?, ?)
                    ");
                    $audit->execute([
                        $_SESSION['user_id'],
                        "Requested replacement for meter {$meter_number}"
                    ]);

                    $pdo->commit();

                    $message = "Replacement request submitted successfully.";

                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "System error occurred.";
                }
            }
        }
    }
}

/* =====================================================
   LOAD MASTER LAYOUT
===================================================== */

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

<div class="main-content">

    <!-- Breadcrumb -->
    <div class="breadcrumb">
        Dashboard › Inventory › Replacement Request
    </div>

    <!-- Page Header -->
    <div class="page-header">
        <h2>Request Meter Replacement</h2>
        <p class="page-subtitle">
            Submit a replacement request for an installed faulty meter.
        </p>
    </div>

    <!-- Card -->
    <div class="table-wrap" style="max-width:600px; padding:30px;">

        <?php if ($error): ?>
            <div class="status-badge red" style="margin-bottom:15px;">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <?php if ($message): ?>
            <div class="status-badge green" style="margin-bottom:15px;">
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>

        <form method="POST">

            <div style="margin-bottom:15px;">
                <label>Full Meter Number *</label>
                <input type="text" name="meter_number" required>
            </div>

            <div style="margin-bottom:15px;">
                <label>Reason for Replacement *</label>
                <textarea name="reason" rows="4" required></textarea>
            </div>

            <button class="action-btn">
                Submit Replacement Request
            </button>

        </form>

    </div>

</div>

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