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

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

/* =========================================
   HANDLE APPROVE / REJECT (POST)
========================================= */

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

    $registrationId = (int)($_POST['registration_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    if (!$registrationId || !in_array($action, ['approve','reject'], true)) {
        $errors[] = "Invalid request.";
    } else {

        try {

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("
                SELECT * FROM meter_registrations 
                WHERE id = ? AND status = 'SUBMITTED'
            ");
            $stmt->execute([$registrationId]);
            $registration = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$registration) {
                throw new Exception("Invalid or already processed registration.");
            }

            $meterId = (int)$registration['meter_id'];

            if ($action === 'approve') {

                /* Update meter to INSTALLED */
                $updateMeter = $pdo->prepare("
                    UPDATE meters 
                    SET status = 'INSTALLED'
                    WHERE id = ?
                ");
                $updateMeter->execute([$meterId]);

                /* Update registration */
                $updateReg = $pdo->prepare("
                    UPDATE meter_registrations
                    SET status = 'APPROVED',
                        approved_by_user_id = ?,
                        approved_at = NOW()
                    WHERE id = ?
                ");
                $updateReg->execute([$_SESSION['user_id'], $registrationId]);

                /* Log movement */
                $movement = $pdo->prepare("
                    INSERT INTO meter_movements
                    (meter_id, movement_type, reason, moved_by_user_id)
                    VALUES (?, 'REGISTERED', 'Meter registration approved', ?)
                ");
                $movement->execute([$meterId, $_SESSION['user_id']]);

                $success = "Registration approved successfully.";

            } else {

                /* Reject registration */
                $updateReg = $pdo->prepare("
                    UPDATE meter_registrations
                    SET status = 'REJECTED',
                        approved_by_user_id = ?,
                        approved_at = NOW()
                    WHERE id = ?
                ");
                $updateReg->execute([$_SESSION['user_id'], $registrationId]);

                $success = "Registration rejected.";
            }

            /* Audit log */
            $audit = $pdo->prepare("
                INSERT INTO audit_logs
                (user_id, action)
                VALUES (?, ?)
            ");
            $audit->execute([
                $_SESSION['user_id'],
                ucfirst($action) . " registration ID {$registrationId}"
            ]);

            $pdo->commit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = $e->getMessage();
        }
    }
}

/* =========================================
   FETCH PENDING REGISTRATIONS
========================================= */

$registrations = $pdo->query("
    SELECT mr.*, m.meter_number
    FROM meter_registrations mr
    JOIN meters m ON mr.meter_id = m.id
    WHERE mr.status = 'SUBMITTED'
    ORDER BY mr.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

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

$breadcrumb = "Approve Registrations";
require_once __DIR__ . '/../includes/layout.php';
?>

<div class="page-header">
    <h2>Pending Registrations</h2>
    <p class="page-subtitle">
        Review and approve submitted meter installations.
    </p>
</div>

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

        <?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; ?>

        <table>
            <thead>
                <tr>
                    <th>Meter</th>
                    <th>Customer</th>
                    <th>Property</th>
                    <th>Installation Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>

            <?php if (empty($registrations)): ?>
                <tr>
                    <td colspan="5">No pending registrations.</td>
                </tr>
            <?php endif; ?>

            <?php foreach ($registrations as $reg): ?>
                <tr>
                    <td><?= htmlspecialchars($reg['meter_number']) ?></td>
                    <td><?= htmlspecialchars($reg['customer_name']) ?></td>
                    <td><?= htmlspecialchars($reg['property_name']) ?></td>
                    <td><?= htmlspecialchars($reg['installation_date']) ?></td>
                    <td>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="registration_id" value="<?= $reg['id'] ?>">
                            <button name="action" value="approve" style="
                                background:var(--edm-orange);
                                color:white;
                                border:none;
                                padding:6px 10px;
                                border-radius:6px;
                                cursor:pointer;
                                margin-right:5px;
                            ">
                                Approve
                            </button>
                            <button name="action" value="reject" style="
                                background:#dc2626;
                                color:white;
                                border:none;
                                padding:6px 10px;
                                border-radius:6px;
                                cursor:pointer;
                            ">
                                Reject
                            </button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>

            </tbody>
        </table>

    </div>
</div>

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