<?php
/**
 * Get All Booked Date Ranges for an Item
 * File: ajax/get-booked-dates.php
 */

require_once '../app/Core/init.php';

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

$item_id = isset($_GET['item_id']) ? (int)$_GET['item_id'] : 0;

if (!$item_id) {
    echo json_encode(['success' => false, 'message' => 'No item ID']);
    exit;
}

try {
    $db = Database::getInstance();
    
    // Get item total quantity
    $itemSql = "SELECT quantity, title FROM items WHERE id = ?";
    $item = $db->fetch($itemSql, [$item_id]);
    
    if (!$item) {
        echo json_encode(['success' => false, 'message' => 'Item not found']);
        exit;
    }
    
    $totalQuantity = $item['quantity'];
    
    // Get all active bookings (current and future only)
    $bookingsSql = "SELECT 
                    o.start_date, 
                    o.end_date, 
                    o.quantity, 
                    o.order_number,
                    o.status,
                    CONCAT(c.first_name, ' ', c.last_name) as customer_name
                    FROM orders o
                    JOIN customers c ON o.customer_id = c.id
                    WHERE o.item_id = ?
                    AND o.status NOT IN ('cancelled', 'completed')
                    AND o.payment_status = 'paid'
                    AND o.end_date >= CURDATE()
                    ORDER BY o.start_date ASC, o.end_date ASC";
    
    $bookings = $db->fetchAll($bookingsSql, [$item_id]);
    
    // Format bookings for display
    $formattedBookings = [];
    foreach ($bookings as $booking) {
        $availableUnits = $totalQuantity - $booking['quantity'];
        
        $formattedBookings[] = [
            'start_date' => $booking['start_date'],
            'end_date' => $booking['end_date'],
            'booked_quantity' => $booking['quantity'],
            'quantity' => $availableUnits,
            'total_quantity' => $totalQuantity,
            'order_number' => $booking['order_number'],
            'status' => $booking['status']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'total_quantity' => $totalQuantity,
        'bookings' => $formattedBookings,
        'has_bookings' => count($formattedBookings) > 0
    ]);
    
} catch (Exception $e) {
    error_log("Get booked dates error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error fetching bookings']);
}