<?php
// ============================================================
// backend/index.php  — Main API Router
// ============================================================

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/helpers/response.php';
require_once __DIR__ . '/helpers/jwt.php';
require_once __DIR__ . '/middleware/cors.php';
require_once __DIR__ . '/middleware/auth.php';

// Apply CORS headers on every request
cors();

// Log every incoming request for debugging
$logDir = __DIR__ . '/logs';
if (!is_dir($logDir)) mkdir($logDir, 0755, true);
$reqLog = '[' . date('Y-m-d H:i:s') . '] '
        . $_SERVER['REQUEST_METHOD'] . ' '
        . ($_SERVER['REQUEST_URI'] ?? '') . ' | '
        . 'Content-Type: ' . ($_SERVER['CONTENT_TYPE'] ?? 'none') . ' | '
        . 'Files: ' . json_encode(array_keys($_FILES)) . PHP_EOL;
file_put_contents($logDir . '/upload.log', $reqLog, FILE_APPEND | LOCK_EX);

// Parse JSON body globally
$rawBody   = file_get_contents('php://input');
$GLOBALS['body'] = json_decode($rawBody, true) ?? [];

// Route the request
$uri    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri    = rtrim(preg_replace('#/+#', '/', $uri), '/');
$method = $_SERVER['REQUEST_METHOD'];

// Strip /backend from path if accessed via WAMP sub-folder
$uri = preg_replace('#^/healthagency/backend#', '', $uri);
$uri = preg_replace('#^/backend#', '', $uri);

$segments = explode('/', ltrim($uri, '/'));
$resource = $segments[0] ?? '';
$sub      = $segments[1] ?? '';

switch ($resource) {

    // --- AUTH ---
    case 'auth':
        require_once __DIR__ . '/api/auth/AuthController.php';
        $ctrl = new AuthController();
        if ($sub === 'register' && $method === 'POST') { $ctrl->register(); break; }
        if ($sub === 'login'    && $method === 'POST') { $ctrl->login();    break; }
        if ($sub === 'me'       && $method === 'GET')  { $ctrl->me();       break; }
        sendError('Auth route not found', 404); break;

    // --- EVENTS ---
    case 'events':
        require_once __DIR__ . '/api/events/EventController.php';
        $ctrl = new EventController();
        if ($method === 'GET' && $sub === '') { $ctrl->index(); break; }
        if ($method === 'GET')               { $ctrl->show($sub); break; }
        sendError('Events route not found', 404); break;

    // --- CLASSES ---
    case 'classes':
        require_once __DIR__ . '/api/classes/ClassController.php';
        $ctrl = new ClassController();
        if ($method === 'GET'  && $sub === '')       { $ctrl->index();        break; }
        if ($method === 'GET')                        { $ctrl->show($sub);     break; }
        if ($method === 'POST' && $sub === 'enroll') { $ctrl->enroll();       break; }
        if ($method === 'GET'  && $sub === 'mine')   { $ctrl->myClasses();    break; }
        sendError('Classes route not found', 404); break;

    // --- PRODUCTS ---
    case 'products':
        require_once __DIR__ . '/api/products/ProductController.php';
        $ctrl = new ProductController();
        if ($method === 'GET' && $sub === '') { $ctrl->index(); break; }
        if ($method === 'GET')               { $ctrl->show($sub); break; }
        sendError('Products route not found', 404); break;

    // --- ORDERS ---
    case 'orders':
        require_once __DIR__ . '/api/orders/OrderController.php';
        $ctrl = new OrderController();
        if ($method === 'POST' && $sub === '')     { $ctrl->create();  break; }
        if ($method === 'GET'  && $sub === 'mine') { $ctrl->myOrders(); break; }
        if ($method === 'GET')                      { $ctrl->show($sub); break; }
        sendError('Orders route not found', 404); break;

    // --- PAYMENTS ---
    case 'payments':
        require_once __DIR__ . '/api/payments/PaymentController.php';
        $ctrl = new PaymentController();
        if ($method === 'POST' && $sub === 'verify') { $ctrl->verify(); break; }
        sendError('Payments route not found', 404); break;

    // --- ADMIN ---
    // URL patterns:
    //   GET    /admin/classes          → list
    //   POST   /admin/classes          → create
    //   PUT    /admin/classes/5        → update id=5   ($segments = ['admin','classes','5'])
    //   DELETE /admin/classes/5        → delete id=5
    case 'admin':
        require_once __DIR__ . '/api/admin/AdminController.php';
        $ctrl = new AdminController();
        $id   = $segments[2] ?? null;   // FIX: ID is at index 2, not 3

        // classes
        if ($sub === 'classes') {
            if ($method === 'GET'    && !$id)  { $ctrl->getClasses();           break; }
            if ($method === 'POST'   && !$id)  { $ctrl->createClass();          break; }
            if ($method === 'PUT'    && $id)   { $ctrl->updateClass($id);       break; }
            if ($method === 'DELETE' && $id)   { $ctrl->deleteClass($id);       break; }
        }
        // products
        if ($sub === 'products') {
            if ($method === 'GET'    && !$id)  { $ctrl->getProducts();          break; }
            if ($method === 'POST'   && !$id)  { $ctrl->createProduct();        break; }
            if ($method === 'PUT'    && $id)   { $ctrl->updateProduct($id);     break; }
            if ($method === 'DELETE' && $id)   { $ctrl->deleteProduct($id);     break; }
        }
        // events
        if ($sub === 'events') {
            if ($method === 'GET'    && !$id)  { $ctrl->getEvents();            break; }
            if ($method === 'POST'   && !$id)  { $ctrl->createEvent();          break; }
            if ($method === 'PUT'    && $id)   { $ctrl->updateEvent($id);       break; }
            if ($method === 'DELETE' && $id)   { $ctrl->deleteEvent($id);       break; }
        }
        // orders
        if ($sub === 'orders') {
            if ($method === 'GET'    && !$id)  { $ctrl->getOrders();            break; }
            if ($method === 'PUT'    && $id)   { $ctrl->updateOrderStatus($id); break; }
        }
        // users
        if ($sub === 'users') {
            if ($method === 'GET')             { $ctrl->getUsers();             break; }
        }
        // stats
        if ($sub === 'stats') {
            if ($method === 'GET')             { $ctrl->stats();                break; }
        }
        sendError('Admin route not found', 404); break;

    // --- DEBUG: view upload log (admin only) ---
    case 'debug-log':
        requireAdmin();
        $logFile = __DIR__ . '/logs/upload.log';
        header('Content-Type: text/plain');
        if (!file_exists($logFile)) {
            echo "Log file does not exist yet: $logFile\n";
            echo "This means no upload has been attempted since logging was added.\n";
        } else {
            // Show last 200 lines
            $lines = file($logFile);
            $last  = array_slice($lines, -200);
            echo "=== backend/logs/upload.log (last " . count($last) . " lines) ===\n\n";
            echo implode('', $last);
        }
        exit;

    // --- UPLOADS (image library) ---
    case 'uploads':
        require_once __DIR__ . '/api/uploads/UploadController.php';
        $ctrl     = new UploadController();
        $param    = $segments[1] ?? '';
        if ($method === 'POST'   && $param === '')                  { $ctrl->upload();         break; }
        if ($method === 'GET'    && $param === '')                  { $ctrl->index();          break; }
        if ($method === 'GET'    && $param !== '' && is_numeric($param)) { $ctrl->show($param);    break; }
        if ($method === 'DELETE' && $param !== '')                  { $ctrl->delete($param);   break; }
        sendError('Uploads route not found', 404); break;

    default:
        sendError('API endpoint not found', 404);
}
