<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

header('Content-Type: application/json');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method.');
    }

    if (function_exists('verify_csrf')) {
        verify_csrf();
    }

    $orderId = (int)($_POST['order_id'] ?? 0);
    $field   = trim((string)($_POST['field'] ?? ''));
    $value   = trim((string)($_POST['value'] ?? ''));

    if ($orderId <= 0) {
        throw new Exception('Invalid reservation.');
    }

    $allowed = [
        'status' => ['0', '1', '2', '3', '4'],
        'payment_status' => ['0', '1', '2'],
    ];

    if (!isset($allowed[$field])) {
        throw new Exception('Invalid field.');
    }

    if (!in_array($value, $allowed[$field], true)) {
        throw new Exception('Invalid value.');
    }

    $stmt = $pdo->prepare("UPDATE orders SET {$field} = :value WHERE id = :id LIMIT 1");
    $stmt->execute([
        ':value' => $value,
        ':id' => $orderId,
    ]);

    echo json_encode([
        'ok' => true,
        'message' => 'Reservation updated successfully.',
    ]);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode([
        'ok' => false,
        'message' => $e->getMessage(),
    ]);
}