<?php
/**
 * Cancel Reservation API
 * Handle reservation cancellations
 */

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

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

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Not authenticated'
    ]);
    exit();
}

$userId = getCurrentUserId();
$reservationId = isset($_POST['id']) ? intval($_POST['id']) : 0;

if (!$reservationId) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Reservation ID is required'
    ]);
    exit();
}

// Verify the reservation belongs to the current user
$sql = "SELECT * FROM reservations WHERE id = ? AND user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ii', $reservationId, $userId);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    http_response_code(403);
    echo json_encode([
        'success' => false,
        'message' => 'Reservation not found or unauthorized'
    ]);
    exit();
}

$reservation = $result->fetch_assoc();

// Check if reservation can be cancelled
if ($reservation['status'] === 'cancelled' || $reservation['status'] === 'checked_out') {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'This reservation cannot be cancelled'
    ]);
    exit();
}

// Cancel the reservation
try {
    $updateSql = "UPDATE reservations SET status = 'cancelled', updated_at = NOW() WHERE id = ?";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bind_param('i', $reservationId);

    if ($updateStmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Reservation cancelled successfully'
        ]);
    } else {
        throw new Exception('Failed to cancel reservation');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error cancelling reservation: ' . $e->getMessage()
    ]);
}
?>
