<?php

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

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

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

$method = $_SERVER['REQUEST_METHOD'];
$uri    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri    = rtrim(str_replace('/meter-reading-api', '', $uri), '/');

// Route table: [method, segments (null = dynamic param), handler, auth, admin_only]
$routes = [
    // Auth
    ['POST',   ['api', 'check-device'],                    'check_device',      false, false],
    ['POST',   ['api', 'login'],                           'login',             false, false],
    ['POST',   ['api', 'logout'],                          'logout',            true,  false],
    ['POST',   ['api', 'change-password'],                 'change_password',   true,  false],

    // Employee
    ['POST',   ['api', 'submit-reading'],                  'submit_reading',    true,  false],
    ['GET',    ['api', 'reading-history'],                 'reading_history',   true,  false],
    ['GET',    ['api', 'profile'],                         'profile',           true,  false],
    ['GET',    ['api', 'menu'],                            'menu',              true,  false],

    // Admin – Dashboard
    ['GET',    ['api', 'dashboard'],                       'dashboard',         true,  true],

    // Admin – Users
    ['GET',    ['api', 'users'],                           'users',             true,  true],
    ['POST',   ['api', 'users'],                           'users',             true,  true],
    ['GET',    ['api', 'users', null],                     'user',              true,  true],
    ['PUT',    ['api', 'users', null],                     'user',              true,  true],
    ['DELETE', ['api', 'users', null],                     'user',              true,  true],
    ['PATCH',  ['api', 'users', null, 'status'],           'user',              true,  true],

    // Admin – Roles & Permissions
    ['GET',    ['api', 'roles'],                           'roles',             true,  true],
    ['POST',   ['api', 'roles'],                           'roles',             true,  true],
    ['PUT',    ['api', 'roles', null],                     'roles',             true,  true],
    ['POST',   ['api', 'roles', null, 'permissions'],      'role_permissions',  true,  true],
    ['GET',    ['api', 'permissions'],                     'permissions_list',  true,  false],

    // Admin – Reports
    ['GET',    ['api', 'reports', 'summary'],              'reports',           true,  true],
    ['GET',    ['api', 'reports', 'daily'],                'reports',           true,  true],
    ['GET',    ['api', 'reports', 'monthly'],              'reports',           true,  true],
    ['GET',    ['api', 'reports', 'export'],               'reports',           true,  true],
];

function matchRoute($routeSegs, $uriParts, &$params) {
    if (count($routeSegs) !== count($uriParts)) return false;
    $params = [];
    foreach ($routeSegs as $i => $seg) {
        if ($seg === null) {
            $params[] = $uriParts[$i];
        } elseif ($seg !== $uriParts[$i]) {
            return false;
        }
    }
    return true;
}

$uriParts = array_values(array_filter(explode('/', $uri), fn($s) => $s !== ''));
$matched  = false;

foreach ($routes as [$routeMethod, $routeSegs, $handler, $requiresAuth, $adminOnly]) {
    $params = [];
    if ($routeMethod !== $method) continue;
    if (!matchRoute($routeSegs, $uriParts, $params)) continue;

    $matched = true;
    $GLOBALS['route_params'] = $params;

    if ($requiresAuth) {
        $authPayload = authenticate();
        $GLOBALS['auth_user'] = $authPayload;
        if ($adminOnly) requireAdmin($authPayload);
    }

    require_once __DIR__ . '/api/' . $handler . '.php';
    break;
}

if (!$matched) {
    sendError('Endpoint not found', 404);
}
