<?php
/**
 * Hostiva v6 - Complete API Router (FIXED + WhatsApp + AI Concierge)
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

require __DIR__ . '/bootstrap.php';

try {
    $db = db();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Load controllers and services
require __DIR__ . '/controllers/auth.php';
require __DIR__ . '/controllers/bookings_complete.php';
require __DIR__ . '/controllers/invoices_complete.php';
require __DIR__ . '/controllers/ota_sync.php';
require __DIR__ . '/controllers/housekeeping_complete.php';
require __DIR__ . '/controllers/dashboard_stats.php';
require __DIR__ . '/controllers/service_tickets.php';
require __DIR__ . '/controllers/whatsapp.php';
require __DIR__ . '/controllers/whatsapp_webhook.php';
require __DIR__ . '/services/EmailService.php';
require __DIR__ . '/services/PaymentService.php';
require __DIR__ . '/services/OTAIntegrationService.php';

// Parse request
$config = $GLOBALS['CONFIG'] ?? require __DIR__ . '/../config/config.php';
$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$request_method = $_SERVER['REQUEST_METHOD'];
$json_data = json_decode(file_get_contents('php://input'), true) ?? [];

$base_path = '/hostiva/api';
$route = str_replace($base_path, '', $request_uri);
$parts = array_filter(explode('/', $route));
$parts = array_values($parts);

// Initialize controllers
$auth_controller = new AuthController($db, $config);
$bookings_controller = new BookingsController($db, $config);
$invoices_controller = new InvoicesController($db, $config);
$ota_service = new OTAIntegrationService($db, $config);
$ota_controller = new OTASyncController($db, $config, $ota_service);
$email_service = new EmailService($db, $config);
$payment_service = new PaymentService($db, $config);
$housekeeping_controller = new HousekeepingController($db, $config);
$dashboard_controller = new DashboardStatsController($db);
$tickets_controller = new ServiceTicketsController($db, $config);

// Get auth token
$headers = function_exists('apache_request_headers') ? apache_request_headers() : [];
$auth_token = $headers['Authorization'] ?? $_GET['token'] ?? null;
if ($auth_token) {
    $auth_token = str_replace('Bearer ', '', $auth_token);
}

try {
    if (empty($parts[0])) {
        echo json_encode(['success' => true, 'message' => 'Hostiva API v6']);
        exit;
    }

    if ($parts[0] === 'auth') {
        if (($parts[1] ?? '') === 'login' && $request_method === 'POST') {
            echo json_encode($auth_controller->login($json_data));
        } elseif (($parts[1] ?? '') === 'register' && $request_method === 'POST') {
            echo json_encode($auth_controller->register($json_data));
        } elseif (($parts[1] ?? '') === 'logout' && $request_method === 'POST') {
            echo json_encode($auth_controller->logout($auth_token));
        } elseif (($parts[1] ?? '') === 'verify' && $request_method === 'GET') {
            echo json_encode($auth_controller->verify($auth_token));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'bookings') {
        if (empty($parts[1]) && $request_method === 'GET') {
            echo json_encode($bookings_controller->getAll($_GET));
        } elseif (empty($parts[1]) && $request_method === 'POST') {
            $json_data['user_id'] = getUserIdFromToken($db, $auth_token);
            echo json_encode($bookings_controller->create($json_data));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && $request_method === 'GET') {
            echo json_encode($bookings_controller->getById($parts[1]));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && $request_method === 'PUT') {
            $json_data['user_id'] = getUserIdFromToken($db, $auth_token);
            echo json_encode($bookings_controller->update($parts[1], $json_data));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && $request_method === 'DELETE') {
            echo json_encode($bookings_controller->cancel($parts[1], $json_data['reason'] ?? null));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && ($parts[2] ?? '') === 'guest-link' && $request_method === 'POST') {
            echo json_encode($bookings_controller->generateGuestLink($parts[1]));
        } elseif (($parts[1] ?? '') === 'guest' && !empty($parts[2]) && $request_method === 'GET') {
            echo json_encode($bookings_controller->getByGuestToken($parts[2]));
        } elseif (($parts[1] ?? '') === 'availability' && $request_method === 'POST') {
            echo json_encode($bookings_controller->checkAvailability($json_data));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'invoices') {
        if (empty($parts[1]) && $request_method === 'GET') {
            echo json_encode($invoices_controller->getAll($_GET));
        } elseif (empty($parts[1]) && $request_method === 'POST') {
            echo json_encode($invoices_controller->generate($json_data['booking_id'] ?? null, getUserIdFromToken($db, $auth_token)));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && $request_method === 'GET') {
            echo json_encode($invoices_controller->getById($parts[1]));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'payments') {
        if (($parts[1] ?? '') === 'stripe-key' && $request_method === 'GET') {
            echo json_encode($payment_service->getPublicKey());
        } elseif (($parts[1] ?? '') === 'create-intent' && $request_method === 'POST') {
            echo json_encode($payment_service->createPaymentIntent($json_data['invoice_id'] ?? null));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'housekeeping') {
        if (empty($parts[1]) && $request_method === 'GET') {
            echo json_encode($housekeeping_controller->getTasks($_GET));
        } elseif (empty($parts[1]) && $request_method === 'POST') {
            echo json_encode($housekeeping_controller->createTask($json_data));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'service-tickets') {
        if (empty($parts[1]) && $request_method === 'GET') {
            echo json_encode($tickets_controller->getAll($_GET));
        } elseif (empty($parts[1]) && $request_method === 'POST') {
            echo json_encode($tickets_controller->create($json_data));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && $request_method === 'GET') {
            echo json_encode($tickets_controller->getById($parts[1]));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && ($parts[2] ?? '') === 'status' && $request_method === 'PUT') {
            echo json_encode($tickets_controller->updateStatus($parts[1], $json_data['status'], null, $json_data['notes'] ?? null));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && ($parts[2] ?? '') === 'assign' && $request_method === 'POST') {
            echo json_encode($tickets_controller->assign($parts[1], $json_data['user_id']));
        } elseif (!empty($parts[1]) && is_numeric($parts[1]) && ($parts[2] ?? '') === 'rate' && $request_method === 'POST') {
            echo json_encode($tickets_controller->rateTicket($parts[1], $json_data['rating'], $json_data['feedback'] ?? null));
        } elseif (($parts[1] ?? '') === 'stats' && $request_method === 'GET') {
            echo json_encode($tickets_controller->getDashboardStats($_GET['property_id'] ?? 1));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'ai-concierge') {
        require_once __DIR__ . '/controllers/ai_concierge.php';
        $ai = new AIConciergeController($db, $config);
        if ($request_method === 'POST') {
            echo json_encode($ai->handleQuery($json_data));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'dashboard') {
        if (($parts[1] ?? '') === 'stats' && $request_method === 'GET') {
            echo json_encode($dashboard_controller->getStats($_GET['property_id'] ?? null));
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
        }

    } elseif ($parts[0] === 'webhook' && ($parts[1] ?? '') === 'whatsapp') {
        // Inbound WhatsApp (provider-called, NO auth). GET=verify handshake, POST=messages/status.
        $wh = new WhatsAppWebhookController($db, $config);
        if ($request_method === 'GET') {
            $wh->verify($_GET);
        } else {
            $raw = file_get_contents('php://input');
            if ($raw === '' || $raw === false) { $raw = json_encode($json_data); }
            $wh->handleInbound($raw, $_GET, function_exists('getallheaders') ? getallheaders() : []);
        }

    } elseif ($parts[0] === 'whatsapp') {
        // Admin endpoints — require a valid session.
        $uid = getUserIdFromToken($db, $auth_token);
        if (!$uid) {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        } else {
            $wa_admin = new WhatsAppController($db, $config);
            $sub = $parts[1] ?? '';
            if ($sub === 'settings' && $request_method === 'GET') {
                echo json_encode($wa_admin->getSettings($_GET['property_id'] ?? 1));
            } elseif ($sub === 'settings' && in_array($request_method, ['POST', 'PUT'], true)) {
                echo json_encode($wa_admin->saveSettings($json_data));
            } elseif ($sub === 'messages' && $request_method === 'GET') {
                echo json_encode($wa_admin->getMessages($_GET));
            } elseif ($sub === 'send' && $request_method === 'POST') {
                echo json_encode($wa_admin->send($json_data));
            } elseif ($sub === 'stats' && $request_method === 'GET') {
                echo json_encode($wa_admin->getStats());
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
            }
        }

    } else {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
    }

} catch (Exception $e) {
    error_log('API Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error']);
}

function getUserIdFromToken($db, $token) {
    try {
        $stmt = $db->prepare("SELECT user_id FROM user_sessions WHERE token = ? AND expires_at > NOW()");
        $stmt->execute([$token]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['user_id'] ?? null;
    } catch (Exception $e) {
        return null;
    }
}
