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

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

/*
|--------------------------------------------------------------------------
| HANDLE ACTION
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $replacementId = (int)$_POST['request_id'];
    $action = $_POST['action'];

    $pdo->beginTransaction();

    try {

        $stmt = $pdo->prepare("
            SELECT * FROM replacement_requests
            WHERE id = ? AND status = 'PENDING'
        ");
        $stmt->execute([$replacementId]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$request) {
            throw new Exception("Invalid request.");
        }

        $oldMeterId = $request['old_meter_id'];

        // Fetch old meter
        $oldMeter = $pdo->prepare("SELECT * FROM meters WHERE id = ?");
        $oldMeter->execute([$oldMeterId]);
        $old = $oldMeter->fetch(PDO::FETCH_ASSOC);

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

        /*
        |--------------------------------------------------------------------------
        | OPTION 1 — REPLACE
        |--------------------------------------------------------------------------
        */
        if ($action === 'replace') {

            $newMeterId = (int)$_POST['new_meter_id'];

            $newMeter = $pdo->prepare("
                SELECT * FROM meters
                WHERE id = ? AND status = 'IN_STOCK'
            ");
            $newMeter->execute([$newMeterId]);
            $new = $newMeter->fetch(PDO::FETCH_ASSOC);

            if (!$new) {
                throw new Exception("Invalid replacement meter.");
            }

            // Old becomes FAULTY
            $pdo->prepare("UPDATE meters SET status='FAULTY' WHERE id=?")
                ->execute([$oldMeterId]);

            // New becomes INSTALLED
            $pdo->prepare("UPDATE meters SET status='INSTALLED' WHERE id=?")
                ->execute([$newMeterId]);

            // Update request
            $pdo->prepare("
                UPDATE replacement_requests
                SET status='APPROVED',
                    new_meter_id=?,
                    approved_by_user_id=?,
                    approved_at=NOW()
                WHERE id=?
            ")->execute([$newMeterId, $_SESSION['user_id'], $replacementId]);

        }

        /*
        |--------------------------------------------------------------------------
        | OPTION 2 — RETURN ONLY
        |--------------------------------------------------------------------------
        */
        if ($action === 'return') {

            // Old meter back to warehouse
            $pdo->prepare("
                UPDATE meters
                SET status='IN_STOCK',
                    current_holder_company_id=NULL
                WHERE id=?
            ")->execute([$oldMeterId]);

            $pdo->prepare("
                UPDATE replacement_requests
                SET status='RETURNED',
                    approved_by_user_id=?,
                    approved_at=NOW()
                WHERE id=?
            ")->execute([$_SESSION['user_id'], $replacementId]);

        }

        $pdo->commit();

        header("Location: approve_replacements.php");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        die($e->getMessage());
    }
}

/*
|--------------------------------------------------------------------------
| FETCH PENDING REQUESTS
|--------------------------------------------------------------------------
*/
$requests = $pdo->query("
    SELECT rr.*, m.meter_number
    FROM replacement_requests rr
    JOIN meters m ON rr.old_meter_id = m.id
    WHERE rr.status = 'PENDING'
    ORDER BY rr.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| FETCH AVAILABLE IN_STOCK METERS
|--------------------------------------------------------------------------
*/
$availableMeters = $pdo->query("
    SELECT id, meter_number
    FROM meters
    WHERE status = 'IN_STOCK'
")->fetchAll(PDO::FETCH_ASSOC);

/* ===== LOAD LAYOUT ===== */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>Approve Replacement Requests</h2>
        <p class="page-subtitle">Approve with new meter or return without replacement.</p>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Old Meter</th>
                    <th>Reason</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>

            <?php foreach ($requests as $req): ?>
            <tr>
                <td><?= htmlspecialchars($req['meter_number']) ?></td>
                <td><?= htmlspecialchars($req['reason']) ?></td>
                <td>

                    <!-- Replace Form -->
                    <form method="POST" style="margin-bottom:6px;">
                        <input type="hidden" name="request_id" value="<?= $req['id'] ?>">
                        <input type="hidden" name="action" value="replace">

                        <select name="new_meter_id" required>
                            <option value="">Select IN_STOCK meter</option>
                            <?php foreach ($availableMeters as $m): ?>
                                <option value="<?= $m['id'] ?>">
                                    <?= htmlspecialchars($m['meter_number']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <button type="submit" class="action-btn">Approve Replace</button>
                    </form>

                    <!-- Return Only -->
                    <form method="POST">
                        <input type="hidden" name="request_id" value="<?= $req['id'] ?>">
                        <input type="hidden" name="action" value="return">
                        <button type="submit" class="action-btn black">
                            Return Only
                        </button>
                    </form>

                </td>
            </tr>
            <?php endforeach; ?>

            </tbody>
        </table>
    </div>

</div>

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