<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Availability API
 * Developer: JOACHIM'S INNOTECH
 */

// Verify authentication
$user_id = verify_api_request();
if (!$user_id) {
    json_response(['error' => 'Authentication required'], 401);
}

// Handle different methods
switch ($method) {
    case 'GET':
        if ($id === 'check') {
            check_availability();
        } elseif ($id === 'rates') {
            get_rates();
        } elseif ($id === 'calendar') {
            get_calendar();
        } elseif ($id === 'room-types') {
            get_room_types();
        } else {
            json_response(['error' => 'Invalid endpoint'], 400);
        }
        break;
        
    default:
        json_response(['error' => 'Method not allowed'], 405);
}

/**
 * Check room availability
 */
function check_availability() {
    // Get parameters
    $check_in = $_GET['check_in'] ?? '';
    $check_out = $_GET['check_out'] ?? '';
    $room_type_id = isset($_GET['room_type_id']) ? (int)$_GET['room_type_id'] : null;
    $adults = (int)($_GET['adults'] ?? 2);
    $children = (int)($_GET['children'] ?? 0);
    
    // Validate required fields
    if (empty($check_in) || empty($check_out)) {
        json_response(['error' => 'Check-in and check-out dates are required'], 400);
    }
    
    if ($check_in >= $check_out) {
        json_response(['error' => 'Check-out date must be after check-in date'], 400);
    }
    
    // Get available rooms
    $available_rooms = get_available_rooms($check_in, $check_out, $room_type_id, $adults, $children);
    
    // Get rates
    $rates = calculate_rates($available_rooms, $check_in, $check_out);
    
    json_response([
        'success' => true,
        'data' => [
            'check_in' => $check_in,
            'check_out' => $check_out,
            'nights' => calculate_nights($check_in, $check_out),
            'adults' => $adults,
            'children' => $children,
            'available_rooms' => $available_rooms,
            'rates' => $rates,
            'summary' => [
                'total_available' => count($available_rooms),
                'price_range' => get_price_range($rates)
            ]
        ]
    ]);
}

/**
 * Get available rooms
 */
function get_available_rooms($check_in, $check_out, $room_type_id = null, $adults = 2, $children = 0) {
    $sql = "
        SELECT 
            r.*,
            rt.type_name,
            rt.base_price,
            rt.max_adults,
            rt.max_children,
            rt.max_occupancy
        FROM rooms r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        WHERE r.is_active = 1
        AND r.status = 'available'
        AND r.room_id NOT IN (
            SELECT room_id 
            FROM reservations 
            WHERE booking_status IN ('confirmed', 'checked_in')
            AND check_in_date < ? AND check_out_date > ?
            AND room_id IS NOT NULL
        )
    ";
    
    $params = [$check_out, $check_in];
    
    if ($room_type_id) {
        $sql .= " AND r.room_type_id = ?";
        $params[] = $room_type_id;
    }
    
    // Filter by capacity
    if ($adults > 0 || $children > 0) {
        $sql .= " AND rt.max_adults >= ? AND (rt.max_adults + rt.max_children) >= ?";
        $params[] = $adults;
        $params[] = $adults + $children;
    }
    
    $sql .= " ORDER BY rt.base_price, r.room_number";
    
    $rooms = db_fetch_all($sql, $params);
    
    // Format response
    $result = [];
    foreach ($rooms as $room) {
        $result[] = [
            'room_id' => $room['room_id'],
            'room_number' => $room['room_number'],
            'room_type_id' => $room['room_type_id'],
            'type_name' => $room['type_name'],
            'floor' => $room['floor'],
            'capacity' => [
                'adults' => $room['max_adults'],
                'children' => $room['max_children'],
                'total' => $room['max_occupancy']
            ],
            'base_price' => (float)$room['base_price']
        ];
    }
    
    return $result;
}

/**
 * Calculate rates for rooms
 */
function calculate_rates($rooms, $check_in, $check_out) {
    $nights = calculate_nights($check_in, $check_out);
    $rates = [];
    
    foreach ($rooms as $room) {
        // In production, apply season multipliers and price rules
        $total = $room['base_price'] * $nights;
        
        $rates[$room['room_id']] = [
            'per_night' => (float)$room['base_price'],
            'total' => (float)$total,
            'nights' => $nights
        ];
    }
    
    return $rates;
}

/**
 * Get price range
 */
function get_price_range($rates) {
    if (empty($rates)) {
        return null;
    }
    
    $prices = array_column($rates, 'total');
    return [
        'min' => min($prices),
        'max' => max($prices)
    ];
}

/**
 * Get rates for room types
 */
function get_rates() {
    $check_in = $_GET['check_in'] ?? '';
    $check_out = $_GET['check_out'] ?? '';
    $room_type_id = isset($_GET['room_type_id']) ? (int)$_GET['room_type_id'] : null;
    
    if (empty($check_in) || empty($check_out)) {
        json_response(['error' => 'Check-in and check-out dates are required'], 400);
    }
    
    $nights = calculate_nights($check_in, $check_out);
    
    // Build query
    $sql = "
        SELECT 
            rt.*,
            rp.rate_plan_id, rp.plan_name, rp.base_rate as plan_rate,
            rp.adjustment_type, rp.adjustment_value,
            s.season_name, s.multiplier as season_multiplier
        FROM room_types rt
        LEFT JOIN rate_plans rp ON rt.room_type_id = rp.room_type_id AND rp.is_active = 1
        LEFT JOIN seasons s ON rp.season_id = s.season_id 
            AND s.start_date <= ? AND s.end_date >= ?
        WHERE rt.is_active = 1
    ";
    
    $params = [$check_in, $check_in];
    
    if ($room_type_id) {
        $sql .= " AND rt.room_type_id = ?";
        $params[] = $room_type_id;
    }
    
    $sql .= " ORDER BY rt.type_name, rp.base_rate";
    
    $rates = db_fetch_all($sql, $params);
    
    // Group by room type
    $grouped = [];
    foreach ($rates as $rate) {
        $type_id = $rate['room_type_id'];
        
        if (!isset($grouped[$type_id])) {
            $grouped[$type_id] = [
                'room_type_id' => $rate['room_type_id'],
                'type_name' => $rate['type_name'],
                'base_price' => (float)$rate['base_price'],
                'plans' => []
            ];
        }
        
        if ($rate['rate_plan_id']) {
            // Calculate effective rate
            $effective_rate = $rate['plan_rate'];
            
            if ($rate['season_multiplier']) {
                $effective_rate *= $rate['season_multiplier'];
            }
            
            if ($rate['adjustment_type'] == 'percentage') {
                $effective_rate *= (1 + $rate['adjustment_value'] / 100);
            } elseif ($rate['adjustment_type'] == 'fixed') {
                $effective_rate += $rate['adjustment_value'];
            }
            
            $grouped[$type_id]['plans'][] = [
                'plan_id' => $rate['rate_plan_id'],
                'plan_name' => $rate['plan_name'],
                'base_rate' => (float)$rate['plan_rate'],
                'effective_rate' => round($effective_rate, 2),
                'season' => $rate['season_name'],
                'total' => round($effective_rate * $nights, 2)
            ];
        }
    }
    
    json_response([
        'success' => true,
        'data' => [
            'check_in' => $check_in,
            'check_out' => $check_out,
            'nights' => $nights,
            'rates' => array_values($grouped)
        ]
    ]);
}

/**
 * Get availability calendar
 */
function get_calendar() {
    $year = (int)($_GET['year'] ?? date('Y'));
    $month = (int)($_GET['month'] ?? date('m'));
    $room_type_id = isset($_GET['room_type_id']) ? (int)$_GET['room_type_id'] : null;
    
    // Validate month
    if ($month < 1 || $month > 12) {
        json_response(['error' => 'Invalid month'], 400);
    }
    
    // Get days in month
    $days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $first_day = mktime(0, 0, 0, $month, 1, $year);
    
    // Get total rooms
    $total_rooms_sql = "SELECT COUNT(*) FROM rooms WHERE is_active = 1";
    if ($room_type_id) {
        $total_rooms_sql .= " AND room_type_id = $room_type_id";
    }
    $total_rooms = db_fetch_value($total_rooms_sql);
    
    $calendar = [];
    
    for ($day = 1; $day <= $days_in_month; $day++) {
        $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
        
        // Get occupied rooms for this date
        $occupied_sql = "
            SELECT COUNT(DISTINCT room_id) 
            FROM reservations 
            WHERE check_in_date <= ? AND check_out_date > ? 
            AND booking_status IN ('confirmed', 'checked_in')
        ";
        $params = [$date, $date];
        
        if ($room_type_id) {
            $occupied_sql .= " AND room_type_id = ?";
            $params[] = $room_type_id;
        }
        
        $occupied = db_fetch_value($occupied_sql, $params);
        $available = $total_rooms - $occupied;
        
        // Get expected arrivals
        $arrivals = db_fetch_value("
            SELECT COUNT(*) FROM reservations 
            WHERE check_in_date = ? AND booking_status IN ('confirmed', 'pending')
        ", [$date]);
        
        // Get expected departures
        $departures = db_fetch_value("
            SELECT COUNT(*) FROM reservations 
            WHERE check_out_date = ? AND booking_status = 'checked_in'
        ", [$date]);
        
        $calendar[] = [
            'date' => $date,
            'day' => $day,
            'day_of_week' => date('N', strtotime($date)),
            'available' => $available,
            'occupied' => $occupied,
            'total' => $total_rooms,
            'occupancy_rate' => $total_rooms > 0 ? round(($occupied / $total_rooms) * 100, 1) : 0,
            'arrivals' => $arrivals,
            'departures' => $departures
        ];
    }
    
    json_response([
        'success' => true,
        'data' => [
            'year' => $year,
            'month' => $month,
            'month_name' => date('F', $first_day),
            'days_in_month' => $days_in_month,
            'calendar' => $calendar
        ]
    ]);
}

/**
 * Get room types with availability
 */
function get_room_types() {
    $check_in = $_GET['check_in'] ?? date('Y-m-d');
    $check_out = $_GET['check_out'] ?? date('Y-m-d', strtotime('+1 day'));
    
    $room_types = db_fetch_all("
        SELECT 
            rt.*,
            COUNT(r.room_id) as total_rooms,
            (
                SELECT COUNT(*) FROM rooms r2
                WHERE r2.room_type_id = rt.room_type_id
                AND r2.is_active = 1
                AND r2.room_id NOT IN (
                    SELECT room_id FROM reservations 
                    WHERE booking_status IN ('confirmed', 'checked_in')
                    AND check_in_date < ? AND check_out_date > ?
                    AND room_id IS NOT NULL
                )
            ) as available_rooms
        FROM room_types rt
        LEFT JOIN rooms r ON rt.room_type_id = r.room_type_id AND r.is_active = 1
        GROUP BY rt.room_type_id
        ORDER BY rt.type_name
    ", [$check_out, $check_in]);
    
    json_response([
        'success' => true,
        'data' => [
            'check_in' => $check_in,
            'check_out' => $check_out,
            'nights' => calculate_nights($check_in, $check_out),
            'room_types' => $room_types
        ]
    ]);
}