<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Availability Calendar AJAX Handler - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/rooms/availability/ajax.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/availability/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define helper functions if they don't exist
if (!function_exists('json_success')) {
    function json_success($data = null, $message = 'Success') {
        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'success',
            'message' => $message,
            'data' => $data
        ]);
        exit;
    }
}

if (!function_exists('json_error')) {
    function json_error($message = 'Error', $errors = null, $status_code = 400) {
        http_response_code($status_code);
        header('Content-Type: application/json');
        $response = [
            'status' => 'error',
            'message' => $message
        ];
        if ($errors !== null) {
            $response['errors'] = $errors;
        }
        echo json_encode($response);
        exit;
    }
}

if (!function_exists('calculate_nights')) {
    function calculate_nights($check_in, $check_out) {
        $start = new DateTime($check_in);
        $end = new DateTime($check_out);
        return $end->diff($start)->days;
    }
}

if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('is_ajax_request')) {
    function is_ajax_request() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
}

// Check if it's an AJAX request
if (!is_ajax_request() && !isset($_GET['test'])) {
    http_response_code(403);
    exit('Direct access not permitted');
}

// Get action
$action = $_GET['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'get_details':
        get_details();
        break;
        
    case 'check_availability':
        check_availability();
        break;
        
    case 'get_room_types':
        get_room_types();
        break;
        
    case 'get_month_stats':
        get_month_stats();
        break;
        
    default:
        if (isset($_GET['test'])) {
            echo "AJAX endpoint is working. Action parameter is required.";
        } else {
            json_error('Invalid action');
        }
}

/**
 * Get detailed availability for a specific date and room type
 */
function get_details() {
    global $base_path;
    
    $date = $_GET['date'] ?? '';
    $room_type_id = (int)($_GET['room_type_id'] ?? 0);
    
    if (empty($date) || !$room_type_id) {
        echo '<div class="alert alert-danger">Invalid parameters</div>';
        return;
    }
    
    try {
        // Get room type info
        $room_type = db_fetch_one("SELECT * FROM room_types WHERE room_type_id = ?", [$room_type_id]);
        
        if (!$room_type) {
            echo '<div class="alert alert-danger">Room type not found</div>';
            return;
        }
        
        // Get all rooms of this type
        $rooms = db_fetch_all("
            SELECT r.*
            FROM rooms r
            WHERE r.room_type_id = ? AND r.is_active = 1
            ORDER BY r.room_number
        ", [$room_type_id]) ?: [];
        
        // Get reservations for this date
        $reservations = db_fetch_all("
            SELECT 
                r.*,
                g.first_name,
                g.last_name,
                rm.room_number
            FROM reservations r
            JOIN guests g ON r.guest_id = g.guest_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.room_type_id = ?
            AND r.booking_status IN ('confirmed', 'checked_in')
            AND r.check_in_date <= ? 
            AND r.check_out_date > ?
            ORDER BY rm.room_number
        ", [$room_type_id, $date, $date]) ?: [];
        
        // Get maintenance tickets for this date
        $maintenance = db_fetch_all("
            SELECT 
                m.*,
                r.room_number
            FROM maintenance_tickets m
            JOIN rooms r ON m.room_id = r.room_id
            WHERE r.room_type_id = ?
            AND m.status IN ('open', 'in_progress')
            AND m.created_at <= ?
            AND (m.resolved_at IS NULL OR m.resolved_at > ?)
        ", [$room_type_id, $date, $date]) ?: [];
        
        // Create a map of reservations by room_id
        $reservation_map = [];
        foreach ($reservations as $res) {
            $reservation_map[$res['room_id']] = $res;
        }
        
        // Create a map of maintenance by room_id
        $maintenance_map = [];
        foreach ($maintenance as $m) {
            $maintenance_map[$m['room_id']] = $m;
        }
        
        // Count statistics
        $available_count = 0;
        $occupied_count = 0;
        $maintenance_count = 0;
        
        // Build HTML response
        ?>
        <div class="container-fluid">
            <div class="row mb-3">
                <div class="col-md-8">
                    <h5><?php echo escape_html($room_type['type_name'] ?? ''); ?> - <?php echo format_date($date); ?></h5>
                </div>
                <div class="col-md-4 text-end">
                    <span class="badge bg-info me-1">Total: <?php echo count($rooms); ?></span>
                    <span class="badge bg-success me-1" id="availableCount">0</span>
                    <span class="badge bg-danger me-1" id="occupiedCount">0</span>
                    <span class="badge bg-warning" id="maintenanceCount">0</span>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>Room #</th>
                            <th>Floor</th>
                            <th>Status</th>
                            <th>Guest</th>
                            <th>Booking</th>
                            <th>Check-out</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rooms as $room): 
                            $room_id = $room['room_id'] ?? 0;
                            $has_reservation = isset($reservation_map[$room_id]);
                            $has_maintenance = isset($maintenance_map[$room_id]);
                            $reservation = $has_reservation ? $reservation_map[$room_id] : null;
                            
                            if ($has_reservation) {
                                $occupied_count++;
                            } elseif ($has_maintenance) {
                                $maintenance_count++;
                            } else {
                                $available_count++;
                            }
                        ?>
                        <tr>
                            <td><strong><?php echo escape_html($room['room_number'] ?? ''); ?></strong></td>
                            <td><?php echo escape_html($room['floor'] ?? '-'); ?></td>
                            <td>
                                <?php if ($has_reservation): ?>
                                    <span class="badge bg-danger">Occupied</span>
                                <?php elseif ($has_maintenance): ?>
                                    <span class="badge bg-warning">Maintenance</span>
                                <?php else: ?>
                                    <span class="badge bg-success">Available</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($has_reservation): ?>
                                    <a href="/HMSPOS/guests/guests/view.php?id=<?php echo $reservation['guest_id'] ?? 0; ?>" target="_blank">
                                        <?php echo escape_html(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?>
                                    </a>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($has_reservation): ?>
                                    <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $reservation['reservation_id'] ?? 0; ?>" target="_blank">
                                        <?php echo escape_html($reservation['booking_code'] ?? ''); ?>
                                    </a>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo $has_reservation ? format_date($reservation['check_out_date'] ?? '') : '-'; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-info">
                            <th colspan="6">
                                Summary: 
                                <span class="badge bg-success ms-2"><?php echo $available_count; ?> Available</span>
                                <span class="badge bg-danger ms-1"><?php echo $occupied_count; ?> Occupied</span>
                                <span class="badge bg-warning ms-1"><?php echo $maintenance_count; ?> Maintenance</span>
                            </th>
                        </tr>
                    </tfoot>
                </table>
            </div>
            
            <div class="row mt-3">
                <div class="col-12">
                    <a href="/HMSPOS/reservations/reservations/create.php?room_type_id=<?php echo $room_type_id; ?>&check_in=<?php echo $date; ?>" 
                       class="btn btn-sm btn-success" target="_blank">
                        <i class="fas fa-plus-circle"></i> Create Booking
                    </a>
                </div>
            </div>
        </div>
        
        <script>
        // Update the counts in the header
        document.getElementById('availableCount').textContent = '<?php echo $available_count; ?> Available';
        document.getElementById('occupiedCount').textContent = '<?php echo $occupied_count; ?> Occupied';
        document.getElementById('maintenanceCount').textContent = '<?php echo $maintenance_count; ?> Maintenance';
        </script>
        <?php
        
    } catch (Exception $e) {
        error_log("get_details error: " . $e->getMessage());
        echo '<div class="alert alert-danger">Error loading details: ' . escape_html($e->getMessage()) . '</div>';
    }
}

/**
 * Check availability for a date range
 */
function check_availability() {
    $check_in = $_POST['check_in'] ?? '';
    $check_out = $_POST['check_out'] ?? '';
    $room_type_id = (int)($_POST['room_type_id'] ?? 0);
    $adults = (int)($_POST['adults'] ?? 2);
    $children = (int)($_POST['children'] ?? 0);
    
    if (empty($check_in) || empty($check_out)) {
        json_error('Check-in and check-out dates are required');
    }
    
    if ($check_in >= $check_out) {
        json_error('Check-out date must be after check-in date');
    }
    
    try {
        // Get available rooms
        $available_rooms = get_room_availability($check_in, $check_out, $room_type_id) ?: [];
        
        // Filter by capacity if needed
        if ($adults > 0 || $children > 0) {
            $available_rooms = array_filter($available_rooms, function($room) use ($adults, $children) {
                return ($room['max_adults'] ?? 2) >= $adults && 
                       (($room['max_adults'] ?? 2) + ($room['max_children'] ?? 1)) >= ($adults + $children);
            });
        }
        
        json_success([
            'available_rooms' => array_values($available_rooms),
            'count' => count($available_rooms),
            'check_in' => $check_in,
            'check_out' => $check_out,
            'nights' => calculate_nights($check_in, $check_out)
        ]);
        
    } catch (Exception $e) {
        error_log("check_availability error: " . $e->getMessage());
        json_error('Error checking availability: ' . $e->getMessage());
    }
}

/**
 * Get room types with availability counts
 */
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'));
    
    try {
        $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_success([
            'room_types' => $room_types,
            'check_in' => $check_in,
            'check_out' => $check_out,
            'nights' => calculate_nights($check_in, $check_out)
        ]);
        
    } catch (Exception $e) {
        error_log("get_room_types error: " . $e->getMessage());
        json_error('Error loading room types: ' . $e->getMessage());
    }
}

/**
 * Get monthly statistics for charts
 */
function get_month_stats() {
    $year = (int)($_GET['year'] ?? date('Y'));
    $month = (int)($_GET['month'] ?? date('m'));
    
    $start_date = "$year-$month-01";
    $end_date = date('Y-m-t', strtotime($start_date));
    
    try {
        // Daily occupancy data
        $daily_data = [];
        $current = strtotime($start_date);
        $end = strtotime($end_date);
        
        while ($current <= $end) {
            $date = date('Y-m-d', $current);
            $occupied = (int)db_fetch_value("
                SELECT COUNT(DISTINCT room_id) FROM reservations 
                WHERE check_in_date <= ? AND check_out_date > ? 
                AND booking_status IN ('confirmed', 'checked_in')
            ", [$date, $date]) ?: 0;
            
            $total = (int)db_fetch_value("SELECT COUNT(*) FROM rooms WHERE is_active = 1") ?: 1;
            $occupancy_rate = round(($occupied / $total) * 100, 1);
            
            $daily_data[] = [
                'date' => $date,
                'day' => (int)date('j', $current),
                'occupied' => $occupied,
                'occupancy_rate' => $occupancy_rate
            ];
            
            $current = strtotime('+1 day', $current);
        }
        
        // Room type distribution
        $room_type_dist = db_fetch_all("
            SELECT 
                rt.type_name,
                COUNT(r.room_id) as total,
                SUM(CASE WHEN r.status = 'occupied' THEN 1 ELSE 0 END) as occupied
            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
        ") ?: [];
        
        json_success([
            'daily' => $daily_data,
            'room_types' => $room_type_dist,
            'month' => $month,
            'year' => $year,
            'month_name' => date('F Y', strtotime($start_date))
        ]);
        
    } catch (Exception $e) {
        error_log("get_month_stats error: " . $e->getMessage());
        json_error('Error loading statistics: ' . $e->getMessage());
    }
}

// Helper function to get room availability (if not defined elsewhere)
if (!function_exists('get_room_availability')) {
    function get_room_availability($check_in, $check_out, $room_type_id = null) {
        $sql = "
            SELECT r.*, rt.type_name, rt.base_price, rt.max_adults, rt.max_children
            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;
        }
        
        $sql .= " ORDER BY rt.base_price, r.room_number";
        
        return db_fetch_all($sql, $params) ?: [];
    }
}
?>