<?php
// --- FINAL DEBUG ATTEMPT to break server cache ---
ini_set('display_errors', 1);
error_reporting(E_ALL);
if (function_exists('opcache_invalidate')) {
    opcache_invalidate(__FILE__, true);
    opcache_invalidate(dirname(__DIR__) . '/app/controllers/LoginController.php', true);
}
// --- END FINAL DEBUG ---

// Start the session at the very top
session_start();
date_default_timezone_set('Asia/Jakarta'); // Set default timezone to Jakarta

// Include the Composer autoloader
require_once dirname(__DIR__) . '/vendor/autoload.php';

require_once dirname(__DIR__) . '/config/db.php';
require_once dirname(__DIR__) . '/app/controllers/AssetController.php';
require_once dirname(__DIR__) . '/app/controllers/MaintenanceController.php';
require_once dirname(__DIR__) . '/app/controllers/ReportController.php';
require_once dirname(__DIR__) . '/app/controllers/TicketController.php';
require_once dirname(__DIR__) . '/app/controllers/SLAController.php';
require_once dirname(__DIR__) . '/app/controllers/DashboardController.php';
require_once dirname(__DIR__) . '/app/controllers/LoginController.php';
require_once dirname(__DIR__) . '/app/controllers/RegisterController.php';
require_once dirname(__DIR__) . '/app/controllers/UserController.php';
require_once dirname(__DIR__) . '/app/controllers/HelpdeskController.php';
require_once dirname(__DIR__) . '/app/controllers/KpiController.php';
require_once dirname(__DIR__) . '/app/controllers/SurveyController.php';

$page = $_GET['page'] ?? 'home';

// --- Authentication & Authorization ---
$publicPages = ['login', 'login_process', 'register', 'register_process', 'helpdesk_report_form', 'helpdesk_submit_report', 'survey_form', 'survey_submit'];
$isLoggedIn = isset($_SESSION['user_id']);

if (!$isLoggedIn && !in_array($page, $publicPages)) {
    header("Location: ?page=login");
    exit();
}

// Redirect logged-in users from the login page to home
if ($isLoggedIn && $page === 'login') {
    header("Location: ?page=home");
    exit();
}

// Role-based access control
$role = $_SESSION['role'] ?? null;
$petugasPages = ['home', 'scan', 'maintenance', 'maintenance_form', 'maintenance_history', 'add_maintenance_process', 'assets', 'add_asset', 'add_asset_process', 'helpdesk_tickets', 'helpdesk_view_ticket', 'helpdesk_update_ticket', 'logout'];
$adminPages = ['users', 'users_create', 'users_store', 'users_edit', 'users_update', 'users_delete', 'reports', 'tickets', 'view_ticket', 'add_ticket', 'add_ticket_process', 'add_ticket_update', 'sla_vendors', 'sla_vendors_create', 'sla_vendors_store', 'sla_incidents', 'sla_incidents_create', 'sla_incidents_store', 'sla_incidents_resolve', 'kpi_it', 'kpi_manual_input_form', 'kpi_process_manual_input', 'survey_results', 'edit_asset', 'edit_asset_process', 'print_all_qrcodes']; // Added new asset editing pages and print all qrcodes

if (!in_array($page, $publicPages) && $role === 'petugas' && !in_array($page, $petugasPages)) {
    // If a 'petugas' tries to access a non-authorized page (and it's not a public page), show an error
    $page = 'unauthorized';
} elseif (!in_array($page, $publicPages) && $role === 'admin' && !in_array($page, $petugasPages) && !in_array($page, $adminPages)) {
    // If an 'admin' tries to access a page not in admin or general petugas pages (and it's not a public page)
    $page = 'unauthorized';
}
// --- End Auth ---


// Instantiate DashboardController early as it's used by get_chart_data endpoint
$dashboardController = new DashboardController();



// Instantiate remaining controllers
$assetController = new AssetController();
$maintenanceController = new MaintenanceController();
$reportController = new ReportController();
$ticketController = new TicketController();
$slaController = new SLAController();
$loginController = new LoginController();
$registerController = new RegisterController();
$userController = new UserController();
$helpdeskController = new HelpdeskController();
$kpiController = new KpiController();
$surveyController = new SurveyController();

// Special handling for public pages that don't use the main layout
if (in_array($page, ['login', 'register', 'helpdesk_report_form', 'survey_form'])) {
    switch ($page) {
        case 'login':
            $loginController->showLoginForm();
            break;
        case 'register':
            $registerController->showRegistrationForm();
            break;
        case 'helpdesk_report_form':
            $helpdeskController->showReportForm();
            break;
        case 'survey_form':
            $surveyController->showSurveyForm();
            break;
        default:
            // Fallback for any other public pages that might be added later
            // and should not use the layout. If needed, this case can be expanded.
            break;
    }
    exit(); // Exit after rendering public page to prevent layout.php inclusion
}

ob_start();

switch ($page) {
    case 'login_process':
        $loginController->login();
        break;
    case 'logout':
        $loginController->logout();
        break;

    case 'helpdesk_submit_report':
        $helpdeskController->submitReport();
        break;
    case 'helpdesk_tickets':
        $helpdeskController->index();
        break;
    case 'helpdesk_view_ticket':
        $helpdeskController->viewTicket();
        break;
    case 'helpdesk_update_ticket':
        $helpdeskController->updateTicket();
        break;
    case 'helpdesk_report_download':
        $helpdeskController->downloadReport();
        break;

    case 'kpi_it':
        $kpiController->index();
        break;
    case 'kpi_manual_input_form':
        $kpiController->showManualInputForm();
        break;
    case 'kpi_process_manual_input':
        $kpiController->processManualInput();
        break;

    case 'survey_submit':
        $surveyController->submitSurvey();
        break;
    case 'survey_results':
        $surveyController->viewSurveyResults();
        break;
        
    case 'home':
        $dashboardController->index();
        break;
    case 'assets':
        $assetController->index();
        break;
    case 'add_asset':
        $assetController->create();
        break;
    case 'add_asset_process':
        $assetController->processCreate();
        break;
    case 'edit_asset': // New
        $assetController->edit();
        break;
    case 'edit_asset_process': // New
        $assetController->processEdit();
        break;
    case 'print_all_qrcodes': // New
        $assetController->printAllQRCodes();
        break;
    case 'scan':
        require_once dirname(__DIR__) . '/views/scan.php';
        break;
    case 'maintenance_form':
        $maintenanceController->showMaintenanceForm();
        break;
    case 'maintenance':
        $maintenanceController->index();
        break;
    case 'maintenance_history':
        $maintenanceController->showAllHistory();
        break;
    case 'add_maintenance_process':
        $maintenanceController->processCreate();
        break;
    case 'reports':
        $reportController->index();
        break;
    case 'tickets':
        $ticketController->index();
        break;
    case 'view_ticket':
        $ticketController->view();
        break;
    case 'add_ticket':
        $ticketController->create();
        break;
    case 'add_ticket_process':
        $ticketController->processCreate();
        break;
    case 'add_ticket_update':
        $ticketController->processUpdate();
        break;
    case 'sla_vendors':
        $slaController->showVendors();
        break;
    case 'sla_vendors_create':
        $slaController->showAddVendorForm();
        break;
    case 'sla_vendors_store':
        $slaController->processAddVendor();
        break;
    case 'sla_incidents':
        $slaController->showIncidents();
        break;
    case 'sla_incidents_create':
        $slaController->showAddIncidentForm();
        break;
    case 'sla_incidents_store':
        $slaController->processAddIncident();
        break;
    case 'sla_incidents_resolve':
        $slaController->processResolveIncident();
        break;

    case 'users':
        $userController->index();
        break;
    case 'users_create':
        $userController->create();
        break;
    case 'users_store':
        $userController->store();
        break;
    case 'users_edit':
        $userController->edit();
        break;
    case 'users_update':
        $userController->update();
        break;
    case 'users_delete':
        $userController->delete();
        break;
    
    case 'unauthorized':
        echo "<h1>Akses Ditolak</h1><p>Anda tidak memiliki izin untuk mengakses halaman ini.</p>";
        break;
    default:
        echo "<h1>404 Halaman Tidak Ditemukan</h1>";
        break;
}

$content = ob_get_clean();

require_once dirname(__DIR__) . '/views/layout.php';
