<?php
/**
 * CHECK AVAILABILITY API
 * File: api/check-availability.php
 * Check if an item is available for rental on specific dates
 */

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

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

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'error' => 'Invalid request method'], 405);
}

// Validate CSRF token
if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
    json_response(['success' => false, 'error' => 'Invalid security token'], 403);
}

// Get and validate input
$item_id = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;
$start_date = Security::clean($_POST['start_date'] ?? '');
$end_date = Security::clean($_POST['end_date'] ?? '');

if ($item_id <= 0) {
    json_response(['success' => false, 'error' => 'Invalid item ID']);
}

if (empty($start_date) || empty($end_date)) {
    json_response(['success' => false, 'error' => 'Start and end dates are required']);
}

// Validate dates
$start = strtotime($start_date);
$end = strtotime($end_date);
$today = strtotime(date('Y-m-d'));

if ($start < $today) {
    json_response(['success' => false, 'error' => 'Start date cannot be in the past']);
}

if ($end <= $start) {
    json_response(['success' => false, 'error' => 'End date must be after start date']);
}

// Check availability
$calendar = new CalendarService();
$is_available = $calendar->isAvailable($item_id, $start_date, $end_date);

if ($is_available) {
    // Calculate pricing
    $item = new Item();
    $item_data = $item->find($item_id);
    
    if ($item_data) {
        $rental_days = ceil(($end - $start) / 86400);
        $subtotal = $rental_days * $item_data['price_per_day'];
        $platform_fee = ($subtotal * PLATFORM_COMMISSION) / 100;
        $total = $subtotal + $platform_fee + $item_data['security_deposit'];
        
        json_response([
            'success' => true,
            'available' => true,
            'pricing' => [
                'rental_days' => $rental_days,
                'price_per_day' => $item_data['price_per_day'],
                'subtotal' => $subtotal,
                'platform_fee' => $platform_fee,
                'security_deposit' => $item_data['security_deposit'],
                'total' => $total,
                'formatted' => [
                    'price_per_day' => format_money($item_data['price_per_day']),
                    'subtotal' => format_money($subtotal),
                    'platform_fee' => format_money($platform_fee),
                    'security_deposit' => format_money($item_data['security_deposit']),
                    'total' => format_money($total)
                ]
            ]
        ]);
    }
}

json_response([
    'success' => true,
    'available' => false,
    'message' => 'Item is not available for the selected dates'
]);