<?php
/**
 * Check Item Availability
 * File: check-availability.php
 * Checks if requested quantity is available for the selected date range
 */

require_once 'app/Core/init.php';

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

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

// Validate inputs
if (!$item_id || !$start_date || !$end_date || !$quantity) {
    echo json_encode([
        'available' => false,
        'message' => 'Missing required parameters'
    ]);
    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 details
    $itemSql = "SELECT id, title, available_quantity, quantity 
                FROM items 
                WHERE id = ? 
                AND status = 'approved' 
                AND approval_status = 'approved' 
                LIMIT 1";
    
    $item = $db->fetch($itemSql, [$item_id]);
    
    if (!$item) {
        echo json_encode([
            'available' => false,
            'message' => 'Item not found or not available'
        ]);
        exit;
    }
    
    // Check if requested quantity exceeds total quantity
    if ($quantity > $item['quantity']) {
        echo json_encode([
            'available' => false,
            'message' => "Only {$item['quantity']} items exist in total. You requested {$quantity}."
        ]);
        exit;
    }
    
    // Check current available quantity
    if ($quantity > $item['available_quantity']) {
        echo json_encode([
            'available' => false,
            'message' => "Only {$item['available_quantity']} items currently available. You requested {$quantity}."
        ]);
        exit;
    }
    
    // Check for overlapping bookings in the date range
    // An order overlaps if:
    // - Its start_date is between our dates OR
    // - Its end_date is between our dates OR
    // - Our dates are completely within the order's dates
    
    $overlapSql = "SELECT 
                    DATE(start_date) as booking_start,
                    DATE(end_date) as booking_end,
                    SUM(quantity) as booked_quantity
                   FROM orders 
                   WHERE item_id = ? 
                   AND status IN ('pending', 'confirmed', 'ongoing')
                   AND (
                       (DATE(start_date) BETWEEN ? AND ?) OR
                       (DATE(end_date) BETWEEN ? AND ?) OR
                       (DATE(start_date) <= ? AND DATE(end_date) >= ?)
                   )
                   GROUP BY DATE(start_date), DATE(end_date)";
    
    $overlapping = $db->fetchAll($overlapSql, [
        $item_id,
        $start_date, $end_date,  // start_date between
        $start_date, $end_date,  // end_date between
        $start_date, $end_date   // completely encompasses
    ]);
    
    if (!empty($overlapping)) {
        $conflictDates = [];
        $maxBookedQuantity = 0;
        
        foreach ($overlapping as $booking) {
            $booked_qty = (int)$booking['booked_quantity'];
            if ($booked_qty > $maxBookedQuantity) {
                $maxBookedQuantity = $booked_qty;
            }
            
            $conflictDates[] = $booking['booking_start'] . ' to ' . $booking['booking_end'] . ' (' . $booked_qty . ' items)';
        }
        
        $available_for_period = $item['quantity'] - $maxBookedQuantity;
        
        if ($quantity > $available_for_period) {
            $dateList = implode('<br>', $conflictDates);
            echo json_encode([
                'available' => false,
                'message' => "Only {$available_for_period} items available for your selected dates.<br><br>
                              <strong>Existing bookings:</strong><br>{$dateList}<br><br>
                              Please select different dates or reduce quantity to {$available_for_period} or less."
            ]);
            exit;
        }
    }
    
    // All checks passed - item is available!
    echo json_encode([
        'available' => true,
        'message' => 'Item is available for booking',
        'available_quantity' => $item['available_quantity'],
        'requested_quantity' => $quantity
    ]);
    
} catch (Exception $e) {
    error_log("Availability check error: " . $e->getMessage());
    echo json_encode([
        'available' => false,
        'message' => 'Error checking availability. Please try again.'
    ]);
}
?>
