<?php
/**
 * Check Item Availability - Uses 'quantity' not 'available_quantity'
 * File: ajax/check-item-availability.php
 */

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

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

$item_id = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;
$start_date = $_POST['start_date'] ?? '';
$end_date = $_POST['end_date'] ?? '';
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;

if (!$item_id || !$start_date || !$end_date) {
    echo json_encode(['available' => false, 'message' => 'Missing required data']);
    exit;
}

// Validate dates
$start = new DateTime($start_date);
$end = new DateTime($end_date);
$today = new DateTime();
$today->setTime(0, 0, 0);

if ($start < $today) {
    echo json_encode(['available' => false, 'message' => 'Start date cannot be in the past']);
    exit;
}

if ($end < $start) {
    echo json_encode(['available' => false, 'message' => 'End date must be on or after start date']);
    exit;
}

try {
    $db = Database::getInstance();
    
    // Get item total quantity - USE 'quantity' not 'available_quantity'
    $itemSql = "SELECT quantity, title FROM items WHERE id = ?";
    $item = $db->fetch($itemSql, [$item_id]);
    
    if (!$item) {
        echo json_encode(['available' => false, 'message' => 'Item not found']);
        exit;
    }
    
    $totalQuantity = $item['quantity'];
    
    // Check availability for EACH day in the range
    $currentDate = clone $start;
    $unavailableDates = [];
    
    while ($currentDate <= $end) {
        $checkDate = $currentDate->format('Y-m-d');
        
        // Get booked quantity for this specific date
        $bookedSql = "SELECT COALESCE(SUM(quantity), 0) as booked_quantity
                      FROM orders
                      WHERE item_id = ?
                      AND status NOT IN ('cancelled', 'completed')
                      AND payment_status = 'paid'
                      AND ? BETWEEN start_date AND end_date";
        
        $result = $db->fetch($bookedSql, [$item_id, $checkDate]);
        $bookedQuantity = $result['booked_quantity'];
        $availableOnDate = $totalQuantity - $bookedQuantity;
        
        if ($availableOnDate < $quantity) {
            $unavailableDates[] = [
                'date' => $checkDate,
                'available' => $availableOnDate,
                'requested' => $quantity
            ];
        }
        
        $currentDate->modify('+1 day');
    }
    
    if (empty($unavailableDates)) {
        echo json_encode([
            'available' => true,
            'message' => "✓ {$quantity} unit(s) available for your selected dates",
            'total_quantity' => $totalQuantity
        ]);
    } else {
        // Build detailed message
        $datesList = [];
        foreach ($unavailableDates as $dateInfo) {
            $formattedDate = date('M j, Y', strtotime($dateInfo['date']));
            $datesList[] = "{$formattedDate} (only {$dateInfo['available']} available)";
        }
        
        $message = "✗ Not enough units available on: " . implode(', ', $datesList);
        
        echo json_encode([
            'available' => false,
            'message' => $message,
            'unavailable_dates' => $unavailableDates,
            'total_quantity' => $totalQuantity
        ]);
    }
    
} catch (Exception $e) {
    error_log("Availability check error: " . $e->getMessage());
    echo json_encode(['available' => false, 'message' => 'Error checking availability']);
}