<?php
// /gabinete/index.php — Roteador principal do sistema
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Configurações globais (BASE_URL, DB_*, etc.)
require_once __DIR__ . '/src/config/config.php';

// Obter a URL solicitada (vinda do .htaccess: index.php?url=...)
$url = $_GET['url'] ?? '';
$url = trim($url, '/');
$segments = $url === '' ? [] : explode('/', $url);

// Se não há URL, redirecionar baseado no login
if (empty($segments)) {
    $logged_in = !empty($_SESSION['user_id']);
    header('Location: ' . BASE_URL . ($logged_in ? '/src/views/dashboard/index.php' : '/login.php'), true, 302);
    exit;
}

// Roteamento principal
$controller = $segments[0] ?? '';
$action = $segments[1] ?? 'index';
$id = $segments[2] ?? null;

try {
    switch ($controller) {

        /* ===================== Eleitores ===================== */
        case 'eleitores':
            require_once __DIR__ . '/src/controllers/EleitoresController.php';
            $controllerObj = new EleitoresController();

            switch ($action) {
                case 'cadastrar':
                case 'create':
                    $controllerObj->create();
                    break;

                case 'store':
                    $controllerObj->store();
                    break;

                case 'ver':
                case 'detalhes':
                    if ($id) {
                        $controllerObj->show($id);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'editar':
                    if ($id) {
                        $controllerObj->edit($id);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'update':
                    $controllerObj->update();
                    break;

                case 'delete':
                    $controllerObj->destroy($id);
                    break;

                default:
                    $controllerObj->index();
                    break;
            }
            break;

        /* ===================== Documentos ===================== */
        case 'documentos':
            require_once __DIR__ . '/src/controllers/DocumentosController.php';
            $controllerObj = new DocumentosController();
            switch ($action) {
                case 'upload':
                    $controllerObj->upload();
                    break;
                default:
                    $controllerObj->index();
                    break;
            }
            break;

        /* ===================== Documents (employees docs) ===================== */
        case 'documents':
            require_once __DIR__ . '/src/controllers/DocumentsController.php';
            $controllerObj = new DocumentsController();
            switch ($action) {
                case 'store':
                    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
                        $controllerObj->store();
                    } else {
                        $controllerObj->index();
                    }
                    break;
                case 'download':
                    if ($id) {
                        $controllerObj->download((int) $id);
                    } else {
                        $controllerObj->index();
                    }
                    break;
                case 'delete':
                    if ($id) {
                        $controllerObj->delete((int) $id);
                    } else {
                        $controllerObj->index();
                    }
                    break;
                default:
                    $controllerObj->index();
                    break;
            }
            break;

        /* ===================== Agendas / Relatórios / Material ===================== */
        case 'agendas':
            require_once __DIR__ . '/src/controllers/AgendasController.php';
            (new AgendasController())->index();
            break;

        case 'relatorios':
            require_once __DIR__ . '/src/controllers/RelatoriosController.php';
            (new RelatoriosController())->index();
            break;

        case 'material-publicitario':
            require_once __DIR__ . '/src/controllers/MaterialPublicitarioController.php';
            (new MaterialPublicitarioController())->index();
            break;

        /* ===================== RH ===================== */
        case 'rh':
            header('Location: ' . BASE_URL . '/src/views/rh/index.php');
            exit;

        /* ===================== PAYROLLS (Folha de Pagamento) ===================== */
        case 'payrolls':
            require_once __DIR__ . '/src/config/db.php';
            require_once __DIR__ . '/src/controllers/PayrollsController.php';
            if (!isset($pdo) || !($pdo instanceof PDO)) {
                throw new Exception('PDO não inicializada');
            }
            $controllerObj = new PayrollsController($pdo);

            $payAction = $segments[1] ?? 'index';
            switch ($payAction) {
                case 'index':
                case '':
                    $controllerObj->index();
                    break;
                case 'show':
                    $idParam = $_GET['id'] ?? null;
                    if ($idParam && ctype_digit((string) $idParam)) {
                        header('Location: ' . BASE_URL . '/src/views/payrolls/create.php?id=' . urlencode((string) $idParam) . '&mode=view');
                        exit;
                    }
                    $controllerObj->index();
                    break;
                case 'edit':
                    $idParam = $_GET['id'] ?? null;
                    if ($idParam && ctype_digit((string) $idParam)) {
                        header('Location: ' . BASE_URL . '/src/views/payrolls/create.php?id=' . urlencode((string) $idParam) . '&mode=edit');
                        exit;
                    }
                    $controllerObj->index();
                    break;
                case 'export':
                    $controllerObj->export();
                    break;
                default:
                    $controllerObj->index();
                    break;
            }
            break;

        /* ===================== EMPLOYEES (Colaboradores) ===================== */
        case 'employees':
            require_once __DIR__ . '/src/controllers/EmployeesController.php';
            $controllerObj = new EmployeesController();

            // atalhos
            $seg1 = $segments[1] ?? null; // pode ser 'create', 'store', '{id}', etc.
            $seg2 = $segments[2] ?? null; // pode ser '{id}' (formato antigo) ou 'edit'/'update'/...
            $seg3 = $segments[3] ?? null; // usado em documentos

            /* --------- Formato REST bonito: /employees/{id} e sub-rotas --------- */
            if ($seg1 !== null && ctype_digit((string) $seg1)) {
                $empId = (int) $seg1;
                $verb = $segments[2] ?? ''; // '', 'edit', 'update', 'delete', 'documents', ...

                // Suporte a documentos: /employees/{id}/documents/{docId}/download|delete
                if ($verb === 'documents' && isset($segments[3]) && ctype_digit((string) $segments[3])) {
                    $docId = (int) $segments[3];
                    $docVerb = $segments[4] ?? 'download';

                    if ($docVerb === 'download') {
                        // GET /employees/{id}/documents/{docId}/download
                        $controllerObj->downloadDocument($empId, $docId);
                        break;
                    }
                    if ($docVerb === 'delete') {
                        // POST (ou GET) /employees/{id}/documents/{docId}/delete
                        $controllerObj->deleteDocument($empId, $docId);
                        break;
                    }
                    // default → volta para show
                    $controllerObj->show($empId);
                    break;
                }

                switch ($verb) {
                    case '':
                        // GET /employees/{id}
                        $controllerObj->show($empId);
                        break;

                    case 'edit':
                        // GET /employees/{id}/edit
                        $controllerObj->edit($empId);
                        break;

                    case 'update':
                        // POST /employees/{id}/update
                        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
                            $controllerObj->update($empId);
                        } else {
                            // se alguém acessou via GET, mostramos o form
                            $controllerObj->edit($empId);
                        }
                        break;

                    case 'delete':
                    case 'destroy':
                        // POST|GET /employees/{id}/delete
                        $controllerObj->destroy($empId);
                        break;

                    default:
                        // Qualquer coisa diferente cai na listagem
                        $controllerObj->index();
                        break;
                }
                break; // encerra case 'employees'
            }

            /* --------- Formato antigo: /employees/show/{id}, /employees/edit/{id}, etc. --------- */
            switch ($action) {
                case 'create':
                case 'cadastrar':
                case 'new':
                    $controllerObj->create();
                    break;

                case 'store':
                    $controllerObj->store();
                    break;

                case 'show':
                case 'ver':
                case 'detalhes':
                    if ($id) {
                        $controllerObj->show((int) $id);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'edit':
                case 'editar':
                    if ($id) {
                        $controllerObj->edit((int) $id);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'update':
                    if ($id) {
                        $controllerObj->update((int) $id);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'delete':
                case 'destroy':
                    if ($id) {
                        $controllerObj->destroy((int) $id);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'delete-multiple':
                    $controllerObj->deleteMultiple();
                    break;

                case 'update-multiple':
                    $controllerObj->updateMultiple();
                    break;

                case 'upload-document':
                    // compat: /employees/upload-document?employee_id=... (se você usar assim)
                    if (!empty($_GET['employee_id'])) {
                        $controllerObj->uploadDocument((int) $_GET['employee_id']);
                    } else {
                        // se não houver employee_id, volta pra lista
                        $controllerObj->index();
                    }
                    break;

                case 'download-document':
                    // compat: /employees/download-document?employee_id=..&document_id=..
                    if (!empty($_GET['employee_id']) && !empty($_GET['document_id'])) {
                        $controllerObj->downloadDocument((int) $_GET['employee_id'], (int) $_GET['document_id']);
                    } else {
                        $controllerObj->index();
                    }
                    break;

                case 'search-by-location':
                    $controllerObj->searchByLocation();
                    break;

                case 'index':
                default:
                    // GET /employees
                    $controllerObj->index();
                    break;
            }
            break;
        /* ===================== FIM employees ===================== */

        /* ===================== Time Records ===================== */
        case 'time-records':
            require_once __DIR__ . '/src/controllers/TimeRecordsController.php';
            $trController = new TimeRecordsController();

            $trAction = $segments[1] ?? 'index';
            $trId = $segments[2] ?? null;

            switch ($trAction) {
                case 'index':
                case '':
                    $trController->index();
                    break;

                case 'clock':
                    if ($trId && ctype_digit((string) $trId)) {
                        $trController->clock((int) $trId);
                    } else {
                        $trController->index();
                    }
                    break;

                case 'clock-in':
                    $trController->clockIn();
                    break;

                case 'clock-out':
                    $trController->clockOut();
                    break;

                case 'start-break':
                    $trController->startBreak();
                    break;

                case 'end-break':
                    $trController->endBreak();
                    break;

                case 'report':
                    $trController->report();
                    break;

                case 'status':
                case 'get-status':
                    $trController->getStatus();
                    break;

                case 'export-csv':
                    $trController->exportCsv();
                    break;

                default:
                    $trController->index();
                    break;
            }
            break;

        /* ===================== Configurações / Usuário ===================== */
        case 'configuracoes':
            require_once __DIR__ . '/src/controllers/ConfiguracoesController.php';
            (new ConfiguracoesController())->index();
            break;

        case 'usuario':
            require_once __DIR__ . '/src/controllers/UsuarioController.php';
            $controllerObj = new UsuarioController();
            switch ($action) {
                case 'login':
                    $controllerObj->login();
                    break;
                case 'logout':
                    $controllerObj->logout();
                    break;
                default:
                    $controllerObj->login();
                    break;
            }
            break;

        /* ===================== Painel Admin ===================== */
        case 'paineladmin':
            require_once __DIR__ . '/src/controllers/PaineladminController.php';
            $paController = new PaineladminController();
            $paAction = $segments[1] ?? 'index';
            switch ($paAction) {
                case '':
                case 'index':
                    $paController->index();
                    break;
                case 'usuarios':
                    $paController->usuarios();
                    break;
                case 'criarUsuario':
                    $paController->criarUsuario();
                    break;
                case 'niveisAcesso':
                    $paController->niveisAcesso();
                    break;
                case 'atualizarNivelAcesso':
                    $paController->atualizarNivelAcesso();
                    break;
                case 'toggleUsuario':
                    $paController->toggleUsuario();
                    break;
                case 'editarUsuario':
                    if ($id) {
                        $paController->editarUsuario((int) $id);
                    } else {
                        $paController->usuarios();
                    }
                    break;
                case 'atualizarUsuario':
                    $paController->atualizarUsuario();
                    break;
                default:
                    $paController->index();
                    break;
            }
            break;

        /* ===================== Fallback ===================== */
        default:
            // Página não encontrada - redirecionar para dashboard ou login
            $logged_in = !empty($_SESSION['user_id']);
            header('Location: ' . BASE_URL . ($logged_in ? '/src/views/dashboard/index.php' : '/login.php'), true, 302);
            exit;
    }

} catch (Exception $e) {
    // Em caso de erro, redirecionar para dashboard com mensagem de erro
    $_SESSION['error_message'] = 'Erro: ' . $e->getMessage();
    $logged_in = !empty($_SESSION['user_id']);
    header('Location: ' . BASE_URL . ($logged_in ? '/src/views/dashboard/index.php' : '/login.php'), true, 302);
    exit;
}
