<?php

require __DIR__ . '/../config/autoload.php';

use App\Core\Router;
use App\Controllers\AuthController;
use App\Controllers\AdminController;
use App\Controllers\ProfileController;
use App\Controllers\WorkspaceController;
use App\Controllers\KpiSchedulingController;
use App\Controllers\CesarKpiController;

use App\Controllers\JatinderKpiController;

$cfg = require __DIR__ . '/../config/config.php';
date_default_timezone_set($cfg['app']['timezone']);

// Used to cache-bust /assets/css/app.css (and any other static asset) so
// browsers always pick up the latest file after a deployment instead of
// serving a stale cached copy. Bump config.php's app.deployment on release.
define('ASSET_VERSION', $cfg['app']['deployment'] ?? 'dev');

session_set_cookie_params([
    'lifetime' => $cfg['app']['session_lifetime_minutes'] * 60,
    'path'     => '/',
    'httponly' => true,
    'samesite' => 'Lax',
    'secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
]);
session_start();

ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/../storage/app_errors.log');

if ($cfg['app']['env'] === 'local') {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    error_reporting(E_ALL);
    ini_set('display_errors', '0');
}

set_error_handler(function ($severity, $message, $file, $line) {
    error_log("[PHP {$severity}] {$message} in {$file}:{$line}");
    return true; // prevents PHP's default handler from echoing it to the browser
});

set_exception_handler(function (\Throwable $e) use ($cfg) {
    error_log('[UNCAUGHT] ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    if ($cfg['app']['env'] === 'local') {
        echo '<pre>' . htmlspecialchars($e->getMessage() . "\n" . $e->getTraceAsString()) . '</pre>';
    } else {
        echo 'Something went wrong. Please try again or contact your administrator.';
    }
});

$router = new Router();

// ---------- Auth ----------
$auth = new AuthController();
$router->get('/', fn() => Router::redirect('/login'));
$router->get('/login', [$auth, 'showLogin']);
$router->post('/login', [$auth, 'login']);
$router->get('/login/verify', [$auth, 'showVerify']);
$router->post('/login/verify', [$auth, 'verify']);
$router->get('/logout', [$auth, 'logout']);
$router->get('/forgot-password', [$auth, 'showForgotPassword']);
$router->post('/forgot-password/send', [$auth, 'sendResetLink']);
$router->get('/reset-password', [$auth, 'showResetPassword']);
$router->post('/reset-password/save', [$auth, 'resetPassword']);

// ---------- Super Admin Panel ----------
$admin = new AdminController();
$router->get('/admin/users', [$admin, 'users']);
$router->post('/admin/users/create', [$admin, 'userCreate']);
$router->post('/admin/users/toggle', [$admin, 'userToggle']);
$router->post('/admin/users/access', [$admin, 'userUpdateAccess']);
$router->post('/admin/users/reset-password', [$admin, 'userResetPassword']);
$router->post('/admin/users/bulk-generate-credentials', [$admin, 'bulkGenerateCredentials']);
$router->get('/admin/users/bulk-credentials-result', [$admin, 'bulkCredentialsResult']);
$router->get('/admin/audit-logs', [$admin, 'auditLogs']);
$router->get('/admin/departments', [$admin, 'departments']);
$router->post('/admin/departments/create', [$admin, 'departmentCreate']);
$router->post('/admin/departments/toggle', [$admin, 'departmentToggle']);
$router->get('/admin/reset-test-data',  [$admin, 'resetTestData']);
$router->post('/admin/reset-test-data', [$admin, 'resetTestData']);
$router->post('/admin/settings/save', [$admin, 'settingsSave']);
$router->get('/admin/projects', [$admin, 'projects']);
$router->post('/admin/projects/save', [$admin, 'projectSave']);
$router->post('/admin/projects/archive', [$admin, 'projectArchive']);

// ---------- KPI Tracker (Scheduling) - nested under Workspace/Admin Projects ----------
$kpiSched = new KpiSchedulingController();
$router->get('/projects/kpi', [$kpiSched, 'index']);
$router->get('/projects/kpi/modal-done',     [$kpiSched, 'modalDone']);
$router->get('/projects/kpi/my-records', [$kpiSched, 'myRecords']);
$router->get('/projects/kpi/entry', [$kpiSched, 'entryForm']);
$router->post('/projects/kpi/save-draft', [$kpiSched, 'saveDraft']);
$router->post('/projects/kpi/submit', [$kpiSched, 'submit']);
$router->get('/projects/kpi/view', [$kpiSched, 'view']);
$router->get('/projects/kpi/review', [$kpiSched, 'reviewQueue']);
$router->post('/projects/kpi/review-action', [$kpiSched, 'reviewAction']);
$router->post('/projects/kpi/reply', [$kpiSched, 'postReply']);
$router->get('/projects/kpi/notif-open', [$kpiSched, 'notifOpen']);
$router->get('/projects/kpi/company', [$kpiSched, 'companyDashboard']);
$router->post('/projects/kpi/unlock', [$kpiSched, 'unlock']);
$router->get('/projects/kpi/export.csv', [$kpiSched, 'exportCsv']);
$router->get('/projects/kpi/export.xlsx', [$kpiSched, 'exportXlsx']);
$router->get('/projects/kpi/export.pdf', [$kpiSched, 'exportPdf']);

// ---------- César Operations Manager KPI (separate form/table/workflow) ----------
$cesarKpi = new CesarKpiController();
$router->get('/projects/cesar-kpi',              [$cesarKpi, 'index']);
$router->get('/projects/cesar-kpi/my-records',   [$cesarKpi, 'myRecords']);
$router->get('/projects/cesar-kpi/entry',        [$cesarKpi, 'entryForm']);
$router->post('/projects/cesar-kpi/save-draft',  [$cesarKpi, 'saveDraft']);
$router->get('/projects/cesar-kpi/modal-done',   [$cesarKpi, 'modalDone']);
$router->get('/projects/cesar-kpi/view',         [$cesarKpi, 'view']);
$router->get('/projects/cesar-kpi/review',       [$cesarKpi, 'reviewQueue']);
$router->post('/projects/cesar-kpi/review-action', [$cesarKpi, 'reviewAction']);
$router->post('/projects/kpi/revise-score',       [$kpiSched, 'reviewAction']);

// ---------- Profile / 2FA (any logged-in user type) ----------
$profile = new ProfileController();
$router->get('/profile', [$profile, 'show']);
$router->post('/profile/change-password', [$profile, 'changePassword']);
$router->post('/profile/2fa/begin', [$profile, 'beginTwoFactorSetup']);
$router->post('/profile/2fa/confirm', [$profile, 'confirmTwoFactorSetup']);
$router->post('/profile/2fa/disable', [$profile, 'disableTwoFactor']);
$router->get('/change-password', [$profile, 'showForceChangePassword']);
$router->post('/change-password/save', [$profile, 'submitForceChangePassword']);

// ---------- Workspace (managers/employees) ----------
$workspace = new WorkspaceController();
$router->get('/workspace', [$workspace, 'home']);
$router->get('/department', [$workspace, 'department']);
$router->get('/project', [$workspace, 'project']);

// ---------- Jatinder (Accounts) KPI — separate form/table/workflow ----------
$jatKpi = new JatinderKpiController();
$router->get('/projects/jatinder-kpi',              [$jatKpi, 'index']);
$router->get('/projects/jatinder-kpi/my-records',   [$jatKpi, 'myRecords']);
$router->get('/projects/jatinder-kpi/entry',        [$jatKpi, 'entryForm']);
$router->post('/projects/jatinder-kpi/save-draft',  [$jatKpi, 'saveDraft']);
$router->get('/projects/jatinder-kpi/modal-done',   [$jatKpi, 'modalDone']);
$router->get('/projects/jatinder-kpi/view',         [$jatKpi, 'view']);
$router->get('/projects/jatinder-kpi/review',       [$jatKpi, 'reviewQueue']);
$router->post('/projects/jatinder-kpi/review-action', [$jatKpi, 'reviewAction']);
$router->post('/projects/jatinder-kpi/reply',       [$jatKpi, 'postReply']);

// ---------- Developer / Test Admin — View-as-User ----------
use App\Controllers\DevAdminController;
$devAdmin = new DevAdminController();
$router->get('/dev/view-as',            [$devAdmin, 'picker']);
$router->post('/dev/impersonate/start', [$devAdmin, 'start']);
$router->get('/dev/impersonate/stop',   [$devAdmin, 'stop']);

// ---------------------------------------------------------------------
// Employee Onboarding — single unmodified app page + API endpoint
// ---------------------------------------------------------------------
use App\Controllers\OnboardingAppController;
use App\Controllers\OnboardingApiController;
$onboardingApp = new OnboardingAppController();
$onboardingApi = new OnboardingApiController();

$router->get('/onboarding',             [$onboardingApp, 'index']);
$router->get('/onboarding/apply',       [$onboardingApp, 'apply']);
$router->get('/onboarding/embed',       [$onboardingApp, 'embed']);
$router->get('/onboarding/download',    [$onboardingApp, 'download']);
$router->get('/onboarding/notif-open',  [$onboardingApp, 'notifOpen']);
$router->post('/onboarding/notif-read', [$onboardingApp, 'notifRead']);
$router->get('/onboarding/api',         [$onboardingApi, 'handle']);
$router->post('/onboarding/api',        [$onboardingApi, 'handle']);

$router->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
