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

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

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

$errors = [];
$success = "";

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

    $meter_number         = trim($_POST['meter_number'] ?? '');
    $installer_company_id = !empty($_POST['installer_company_id']) ? (int)$_POST['installer_company_id'] : null;
    $property_name        = trim($_POST['property_name'] ?? '');
    $property_address     = trim($_POST['property_address'] ?? '');
    $customer_name        = trim($_POST['customer_name'] ?? '');
    $customer_phone       = trim($_POST['customer_phone'] ?? '');
    $installation_date    = $_POST['installation_date'] ?? '';

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

    if ($property_address === '') {
        $errors[] = "Property address is required.";
    }

    if ($installation_date === '') {
        $errors[] = "Installation date is required.";
    }

    if (empty($errors)) {

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

        if (!$meter) {
            $errors[] = "Meter not found in system.";
        } elseif ($meter['status'] === 'INSTALLED') {
            $errors[] = "This meter is already installed.";
        } else {

            try {

                $pdo->beginTransaction();

                /* Insert registration */
                $stmt = $pdo->prepare("
                    INSERT INTO meter_registrations 
                    (meter_id, installer_company_id, property_name, property_address,
                     customer_name, customer_phone, submitted_channel, installation_date, status)
                    VALUES (?, ?, ?, ?, ?, ?, 'INTERNAL', ?, 'SUBMITTED')
                ");

                $stmt->execute([
                    $meter['id'],
                    $installer_company_id,
                    $property_name,
                    $property_address,
                    $customer_name,
                    $customer_phone,
                    $installation_date
                ]);

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

                $pdo->commit();

                $success = "Registration submitted successfully. Awaiting approval.";

            } catch (PDOException $e) {

                $pdo->rollBack();

                if ($e->getCode() == 23000) {
                    $errors[] = "This meter already has a registration.";
                } else {
                    $errors[] = "System error occurred.";
                }
            }
        }
    }
}

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

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

<div class="page-header">
    <h2>Register Meter</h2>
    <p class="page-subtitle">
        Submit a new meter installation for approval.
    </p>
</div>

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

        <?php if (!empty($success)): ?>
            <div style="margin-bottom:15px; color:#16a34a;">
                <?= htmlspecialchars($success) ?>
            </div>
        <?php endif; ?>

        <?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>Full Meter Number *</label>
                <input type="text" name="meter_number" required>
            </div>

            <div style="margin-bottom:15px;">
                <label>Installer Company ID (optional)</label>
                <input type="number" name="installer_company_id">
            </div>

            <div style="margin-bottom:15px;">
                <label>Property Name</label>
                <input type="text" name="property_name">
            </div>

            <div style="margin-bottom:15px;">
                <label>Property Address *</label>
                <textarea name="property_address" required></textarea>
            </div>

            <div style="margin-bottom:15px;">
                <label>Customer Name</label>
                <input type="text" name="customer_name">
            </div>

            <div style="margin-bottom:15px;">
                <label>Customer Phone</label>
                <input type="text" name="customer_phone">
            </div>

            <div style="margin-bottom:20px;">
                <label>Installation Date *</label>
                <input type="date" name="installation_date" required>
            </div>

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

        </form>

    </div>
</div>

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