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

// Initialize system
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/constants.php';
require_once dirname(__DIR__) . '/config/database.php';
require_once dirname(__DIR__) . '/config/helpers.php';
require_once dirname(__DIR__) . '/config/auth.php';
require_once dirname(__DIR__) . '/config/csrf.php';

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

// Handle CORS for external API access
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Get request parameters
$request_uri = $_SERVER['REQUEST_URI'];
$base_api_path = '/api/';
$endpoint = str_replace($base_api_path, '', parse_url($request_uri, PHP_URL_PATH));
$method = $_SERVER['REQUEST_METHOD'];

// Parse endpoint
$parts = explode('/', trim($endpoint, '/'));
$resource = $parts[0] ?? '';
$id = $parts[1] ?? null;
$subresource = $parts[2] ?? null;

// API documentation
if ($resource === '' || $resource === 'index.php') {
    show_api_documentation();
    exit;
}

// Route to appropriate handler
switch ($resource) {
    case 'auth':
        require_once 'auth.php';
        break;
    case 'reservations':
        require_once 'reservations.php';
        break;
    case 'availability':
        require_once 'availability.php';
        break;
    case 'pos':
        require_once 'pos.php';
        break;
    case 'inventory':
        require_once 'inventory.php';
        break;
    default:
        json_response(['error' => 'Endpoint not found'], 404);
}

/**
 * Show API documentation
 */
function show_api_documentation() {
    $docs = [
        'name' => 'Ruhondo Beach Resort API',
        'version' => '1.0.0',
        'description' => 'RESTful API for hotel management system',
        'endpoints' => [
            [
                'path' => '/api/auth/login',
                'method' => 'POST',
                'description' => 'Authenticate user and get token',
                'parameters' => [
                    'username' => 'string (required)',
                    'password' => 'string (required)'
                ]
            ],
            [
                'path' => '/api/auth/logout',
                'method' => 'POST',
                'description' => 'Invalidate current token',
                'auth' => true
            ],
            [
                'path' => '/api/auth/me',
                'method' => 'GET',
                'description' => 'Get current user info',
                'auth' => true
            ],
            [
                'path' => '/api/reservations',
                'method' => 'GET',
                'description' => 'Get list of reservations',
                'auth' => true,
                'parameters' => [
                    'page' => 'integer (optional)',
                    'limit' => 'integer (optional)',
                    'status' => 'string (optional)',
                    'date_from' => 'date (optional)',
                    'date_to' => 'date (optional)'
                ]
            ],
            [
                'path' => '/api/reservations/{id}',
                'method' => 'GET',
                'description' => 'Get single reservation',
                'auth' => true
            ],
            [
                'path' => '/api/reservations',
                'method' => 'POST',
                'description' => 'Create new reservation',
                'auth' => true
            ],
            [
                'path' => '/api/reservations/{id}',
                'method' => 'PUT',
                'description' => 'Update reservation',
                'auth' => true
            ],
            [
                'path' => '/api/reservations/{id}',
                'method' => 'DELETE',
                'description' => 'Cancel reservation',
                'auth' => true
            ],
            [
                'path' => '/api/availability/check',
                'method' => 'GET',
                'description' => 'Check room availability',
                'auth' => true,
                'parameters' => [
                    'check_in' => 'date (required)',
                    'check_out' => 'date (required)',
                    'room_type_id' => 'integer (optional)',
                    'adults' => 'integer (optional)',
                    'children' => 'integer (optional)'
                ]
            ],
            [
                'path' => '/api/availability/rates',
                'method' => 'GET',
                'description' => 'Get rate information',
                'auth' => true,
                'parameters' => [
                    'check_in' => 'date (required)',
                    'check_out' => 'date (required)',
                    'room_type_id' => 'integer (optional)'
                ]
            ],
            [
                'path' => '/api/pos/products',
                'method' => 'GET',
                'description' => 'Get POS products',
                'auth' => true
            ],
            [
                'path' => '/api/pos/sales',
                'method' => 'POST',
                'description' => 'Create POS sale',
                'auth' => true
            ],
            [
                'path' => '/api/inventory/stock',
                'method' => 'GET',
                'description' => 'Get inventory levels',
                'auth' => true
            ],
            [
                'path' => '/api/inventory/movements',
                'method' => 'POST',
                'description' => 'Record stock movement',
                'auth' => true
            ]
        ],
        'authentication' => 'Bearer token required for authenticated endpoints. Obtain token via /api/auth/login'
    ];
    
    json_response($docs, 200);
}

/**
 * Send JSON response
 */
function json_response($data, $status_code = 200) {
    http_response_code($status_code);
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}