<?php
session_start();
require 'config.php';

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Debug: Log the request
error_log("Bookings API called - Session ID: " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'NOT SET'));
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);

// Release any expired bookings before processing
releaseExpiredBookings($conn);

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    error_log("User not logged in");
    echo json_encode([
        'success' => false,
        'message' => 'User not logged in',
        'bookings' => null
    ]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Fetch all bookings made by user
    $user_id = $_SESSION['user_id'];
    $sql = "SELECT id, name, email, phone, booking_date, booking_time, guests, 
            occasion, table_type, dietary_needs, special_requests, status, created_at 
            FROM bookings WHERE user_id = ? ORDER BY booking_date DESC, booking_time DESC";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        error_log("Database prepare error: " . $conn->error);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Database prepare error: ' . $conn->error,
            'bookings' => null
        ]);
        exit;
    }
    
    $stmt->bind_param("i", $user_id);
    if (!$stmt->execute()) {
        error_log("Database execute error: " . $stmt->error);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Database execute error: ' . $stmt->error,
            'bookings' => null
        ]);
        exit;
    }
    
    $result = $stmt->get_result();
    
    if (!$result) {
        error_log("Get result error: " . $stmt->error);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Failed to get results',
            'bookings' => null
        ]);
        exit;
    }
    
    $bookings = [];
    while ($row = $result->fetch_assoc()) {
        $bookings[] = $row;
    }
    
    error_log("Fetched " . count($bookings) . " bookings for user " . $user_id);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Bookings fetched successfully',
        'bookings' => $bookings
    ]);
    $stmt->close();
} 
elseif ($method === 'POST') {
    // Get JSON input
    $input = json_decode(file_get_contents("php://input"), true);
    $action = isset($input['action']) ? $input['action'] : '';
    
    if ($action === 'delete') {
        // Cancel a booking
        $user_id = $_SESSION['user_id'];
        $booking_id = isset($input['booking_id']) ? intval($input['booking_id']) : 0;
        
        if (!$booking_id) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'Booking ID is required',
                'bookings' => null
            ]);
            exit;
        }
        
        // Check if booking belongs to user and get table info
        $check_sql = "SELECT tb.table_id FROM bookings b
                      LEFT JOIN table_bookings tb ON b.id = tb.booking_id
                      WHERE b.id = ? AND b.user_id = ?";
        $check_stmt = $conn->prepare($check_sql);
        
        if (!$check_stmt) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'Database prepare error: ' . $conn->error,
                'bookings' => null
            ]);
            exit;
        }
        
        $check_stmt->bind_param("ii", $booking_id, $user_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows === 0) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'Booking not found or does not belong to you',
                'bookings' => null
            ]);
            exit;
        }
        
        $booking_info = $check_result->fetch_assoc();
        $table_id = $booking_info['table_id'];
        $check_stmt->close();
        
        // Update booking status to cancelled
        $sql = "UPDATE bookings SET status = 'cancelled' WHERE id = ? AND user_id = ?";
        $stmt = $conn->prepare($sql);
        
        if (!$stmt) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'Database prepare error: ' . $conn->error,
                'bookings' => null
            ]);
            exit;
        }
        
        $stmt->bind_param("ii", $booking_id, $user_id);
        
        if ($stmt->execute()) {
            // Delete table booking relationship
            if (!empty($table_id)) {
                $deleteTableBookingSql = "DELETE FROM table_bookings WHERE booking_id = ?";
                $deleteStmt = $conn->prepare($deleteTableBookingSql);
                if ($deleteStmt) {
                    $deleteStmt->bind_param("i", $booking_id);
                    $deleteStmt->execute();
                    $deleteStmt->close();
                }
                
                // Update table status back to available
                $updateTableSql = "UPDATE restaurant_tables SET status = 'available' WHERE id = ?";
                $updateTableStmt = $conn->prepare($updateTableSql);
                if ($updateTableStmt) {
                    $updateTableStmt->bind_param("i", $table_id);
                    $updateTableStmt->execute();
                    $updateTableStmt->close();
                }
            }
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'message' => 'Booking cancelled successfully',
                'bookings' => null
            ]);
        } else {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'Failed to cancel booking: ' . $conn->error,
                'bookings' => null
            ]);
        }
        $stmt->close();
    } else {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Invalid action',
            'bookings' => null
        ]);
        exit;
    }
} else {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method',
        'bookings' => null
    ]);
    exit;
}

$conn->close();
?>
