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

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

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

$errors = [];

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

    $meter_number  = trim($_POST['meter_number'] ?? '');
    $serial_number = trim($_POST['serial_number'] ?? '');
    $meter_type    = $_POST['meter_type'] ?? '';

    if ($meter_number === '') {
        $errors[] = "Meter number is required.";
    }

    if (!in_array($meter_type, ['ELECTRICITY','WATER'], true)) {
        $errors[] = "Invalid meter type selected.";
    }

    if (empty($errors)) {

        $stmt = $pdo->prepare("
            INSERT INTO meters 
            (meter_number, serial_number, meter_type, status)
            VALUES (?, ?, ?, 'IN_STOCK')
        ");

        $stmt->execute([
            $meter_number,
            $serial_number,
            $meter_type
        ]);

        $meter_id = $pdo->lastInsertId();

        /* Log movement */
        $log = $pdo->prepare("
            INSERT INTO meter_movements 
            (meter_id, movement_type, moved_by_user_id)
            VALUES (?, 'UPLOAD', ?)
        ");

        $log->execute([$meter_id, $_SESSION['user_id']]);

        header("Location: inventory.php");
        exit;
    }
}

/* =========================================
   LOAD UNIVERSAL LAYOUT
========================================= */

$breadcrumb = "Add Meter";
require_once __DIR__ . '/../includes/layout.php';
?>

<div class="page-header">
    <h2>Add New Meter</h2>
    <p class="page-subtitle">
        Register a new meter into the EDM Core inventory.
    </p>
</div>

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

        <?php if (!empty($errors)): ?>
            <div style="margin-bottom:15px; color:#dc2626;">
                <?php foreach ($errors as $error): ?>
                    <div><?= htmlspecialchars($error) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <form method="POST">

            <div style="margin-bottom:15px;">
                <label>Meter Number</label>
                <input type="text" name="meter_number" 
                       value="<?= htmlspecialchars($_POST['meter_number'] ?? '') ?>" 
                       required>
            </div>

            <div style="margin-bottom:15px;">
                <label>Serial Number</label>
                <input type="text" name="serial_number"
                       value="<?= htmlspecialchars($_POST['serial_number'] ?? '') ?>">
            </div>

            <div style="margin-bottom:20px;">
                <label>Meter Type</label>
                <select name="meter_type" required>
                    <option value="">Select Type</option>
                    <option value="ELECTRICITY"
                        <?= (($_POST['meter_type'] ?? '') === 'ELECTRICITY') ? 'selected' : '' ?>>
                        Electricity
                    </option>
                    <option value="WATER"
                        <?= (($_POST['meter_type'] ?? '') === 'WATER') ? 'selected' : '' ?>>
                        Water
                    </option>
                </select>
            </div>

            <button type="submit" style="
                background:var(--edm-orange);
                color:white;
                padding:10px 18px;
                border:none;
                border-radius:6px;
                cursor:pointer;
            ">
                Save Meter
            </button>

        </form>

    </div>
</div>

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