<?php

// ─── Simple URL Router ────────────────────────────────────────────────────────
// All requests are rewritten to index.php via .htaccess.
// The script parses the URI segment after /php-api-server/ to dispatch.

$requestUri    = $_SERVER['REQUEST_URI'] ?? '/';
$path          = parse_url($requestUri, PHP_URL_PATH);

// Identify the application root
$scriptDir     = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'); // e.g. /shopnest/php-api-server
$appRoot       = rtrim(dirname($scriptDir), '/');              // e.g. /shopnest

// Clean the path: remove appRoot and any API-related folder names
$path = str_replace($appRoot, '', $path);
$basePatterns = ['/php-api-server/api/', '/php-api-server/', '/api/'];
foreach ($basePatterns as $bp) {
    if (strpos($path, $bp) === 0) {
        $path = '/' . ltrim(substr($path, strlen($bp)), '/');
        break;
    }
}
$path = '/' . trim(ltrim($path, '/'));
$method        = getMethod();

// ─── Route Table ─────────────────────────────────────────────────────────────
// Format: [HTTP_METHOD, regex_pattern, [Controller, method]]
$routes = [

    // Auth
    ['POST', '#^/auth/register$#',       ['AuthController',    'register']],
    ['POST', '#^/auth/login$#',          ['AuthController',    'login']],
    ['POST', '#^/auth/forgot-password$#', ['AuthController',    'forgotPassword']],
    ['POST', '#^/auth/reset-password$#',  ['AuthController',    'resetPassword']],

    // User
    ['GET',  '#^/user/profile$#',        ['AuthController',    'profile']],
    ['PUT',  '#^/user/profile$#',        ['AuthController',    'updateProfile']],
    ['POST', '#^/user/change-password$#',['AuthController',    'changePassword']],
    ['GET',  '#^/user/status$#',          ['UserController',    'checkStatus']],
    ['POST', '#^/user/fcm-token$#',       ['UserController',    'updateFcmToken']],

    // Categories
    ['GET',  '#^/categories$#',          ['ProductController', 'categories']],
    ['GET',  '#^/categories/(\d+)$#',    ['ProductController', 'categoryById']],

    // Products
    ['GET',  '#^/products$#',            ['ProductController', 'products']],
    ['GET',  '#^/products/trending$#',   ['ProductController', 'trendingProducts']],
    ['GET',  '#^/products/slug/([^/]+)$#',['ProductController', 'productBySlug']],
    ['GET',  '#^/products/(\d+)$#',      ['ProductController', 'productById']],

    // Cart
    ['GET',  '#^/cart$#',                ['CartController',    'getCart']],
    ['POST', '#^/cart/add$#',            ['CartController',    'addToCart']],
    ['POST', '#^/cart/update$#',         ['CartController',    'updateCart']],
    ['POST', '#^/cart/remove$#',         ['CartController',    'removeFromCart']],
    ['POST', '#^/cart/clear$#',          ['CartController',    'clearCart']],

    // Orders
    ['POST', '#^/orders/checkout$#',     ['OrderController',   'checkout']],
    ['POST', '#^/orders/buy-now$#',      ['OrderController',   'buyNowCheckout']],
    ['POST', '#^/orders/verify-payment$#',['OrderController',   'verifyPayment']],
    ['GET',  '#^/orders$#',              ['OrderController',   'listOrders']],
    ['GET',  '#^/orders/(\d+)$#',        ['OrderController',   'orderById']],
    ['POST', '#^/orders/status$#',       ['OrderController',   'updateStatus']],
    ['POST', '#^/orders/return$#',       ['OrderController',   'requestReturn']],

    // ID Verification
    ['POST', '#^/user/verify-id$#',      ['VerificationController', 'submitVerification']],

    // Wishlist
    ['GET',  '#^/wishlist$#',            ['WishlistController', 'getWishlist']],
    ['POST', '#^/wishlist/add$#',        ['WishlistController', 'addToWishlist']],
    ['POST', '#^/wishlist/remove$#',     ['WishlistController', 'removeFromWishlist']],

    // Rentals
    ['GET',  '#^/rentals/my$#',          ['RentalController', 'getMyRentals']],
    ['POST', '#^/rentals/schedule-pickup$#', ['RentalController', 'schedulePickup']],

    // Address
    ['GET',     '#^/user/addresses$#',           ['AddressController', 'getAddresses']],
    ['POST',    '#^/user/addresses/add$#',       ['AddressController', 'addAddress']],
    ['PUT',     '#^/user/addresses/update/(\d+)$#',['AddressController', 'updateAddress']],
    ['DELETE',  '#^/user/addresses/delete/(\d+)$#',['AddressController', 'deleteAddress']],
    ['POST',    '#^/user/addresses/set-default/(\d+)$#',['AddressController', 'setDefault']],
    
    // Unblock
    ['GET',     '#^/user/unblock-details$#',     ['UnblockController', 'getUnblockDetails']],
    ['POST',    '#^/user/initiate-unblock$#',    ['UnblockController', 'initiateUnblock']],
    ['POST',    '#^/user/verify-unblock$#',      ['UnblockController', 'verifyUnblock']],

    // Notifications
    ['GET',     '#^/notifications$#',                  ['NotificationController', 'getNotifications']],
    ['GET',     '#^/notifications/unread-count$#',     ['NotificationController', 'getUnreadCount']],
    ['POST',    '#^/notifications/mark-read$#',        ['NotificationController', 'markAsRead']],
    ['POST',    '#^/notifications/mark-all-read$#',    ['NotificationController', 'markAllAsRead']],
    ['POST',    '#^/notifications/delete$#',           ['NotificationController', 'deleteNotification']],
];

// ─── Dispatch ─────────────────────────────────────────────────────────────────
$matched = false;
foreach ($routes as [$routeMethod, $pattern, [$class, $action]]) {
    if ($method === $routeMethod && preg_match($pattern, $path, $matches)) {
        $params  = array_slice($matches, 1);   // captured groups as ordered params
        $matched = true;
        call_user_func_array([$class, $action], $params);
        break;
    }
}

if (!$matched) {
    sendError("Endpoint not found: {$method} {$path}", 404);
}
