<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * API: Get Room Options
 * Returns room details for the options modal
 */

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

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

// Calculate base path
$base_path = null;
$base_path = dirname(__DIR__, 2); // Go up 2 levels from api/ to HMSPOS/

if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Initialize system
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Require authentication
require_auth();

// Get room ID
$room_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$room_id) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Room ID is required'
    ]);
    exit;
}

try {
    // Get room details
    $room = db_fetch_one("
        SELECT 
            r.*,
            rt.type_name,
            CONCAT(g.first_name, ' ', g.last_name) as guest_name,
            res.check_in_date,
            res.check_out_date,
            res.booking_code
        FROM rooms r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        LEFT JOIN reservations res ON r.room_id = res.room_id 
            AND res.booking_status = 'checked_in'
        LEFT JOIN guests g ON res.guest_id = g.guest_id
        WHERE r.room_id = ? AND r.is_active = 1
    ", [$room_id]);

    if (!$room) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Room not found'
        ]);
        exit;
    }

    // Get pending tasks for this room
    $tasks = db_fetch_all("
        SELECT * FROM hk_tasks 
        WHERE room_id = ? AND status IN ('pending', 'assigned', 'in_progress')
        ORDER BY created_at DESC
    ", [$room_id]);

    echo json_encode([
        'status' => 'success',
        'data' => [
            'room_id' => $room['room_id'],
            'room_number' => $room['room_number'],
            'type_name' => $room['type_name'],
            'status' => $room['status'],
            'housekeeping_status' => $room['housekeeping_status'],
            'guest_name' => $room['guest_name'],
            'check_in_date' => $room['check_in_date'],
            'check_out_date' => $room['check_out_date'],
            'booking_code' => $room['booking_code'],
            'tasks' => $tasks
        ]
    ]);

} catch (Exception $e) {
    error_log("Error in get-room-options: " . $e->getMessage());
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}