<?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';
require_once dirname(__DIR__) . '/app/controllers/ProjectController.php';
require_once dirname(__DIR__) . '/app/controllers/ProductReleaseController.php';
require_once dirname(__DIR__) . '/app/controllers/EvaluationController.php';
require_once dirname(__DIR__) . '/app/controllers/RoomTemperatureController.php';

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

// --- Authentication & Authorization ---
$publicPages = ['login', 'login_process', 'register', 'register_process', 'helpdesk_report_form', 'helpdesk_submit_report', 'survey_form', 'survey_submit', 'evaluation_form', 'evaluation_submit', 'room_temperature_public_report'];
$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', 'helpdesk_report_download', 'logout', 'mark_asset_repaired', 'get_unread_helpdesk_count', 'projects', 'project_create', 'project_store', 'project_show', 'project_store_task', 'project_update_task_status', 'project_update_status', 'project_delete_task', 'product_releases', 'product_release_upload', 'product_release_delete', 'room_temperature', 'room_temperature_history', 'room_temperature_input', 'room_temperature_add_reading'];
$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', 'evaluation_results', 'evaluation_download', 'edit_asset', 'edit_asset_process', 'delete_asset', 'print_all_qrcodes', 'upload_assets_excel', 'sla_vendor_performance', 'mark_asset_repaired']; // 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();
$projectController = new ProjectController();
$productReleaseController = new ProductReleaseController();
$evaluationController = new EvaluationController();
$roomTemperatureController = new RoomTemperatureController();

// Special handling for public pages that don't use the main layout
if (in_array($page, ['login', 'register', 'helpdesk_report_form', 'survey_form', 'evaluation_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;
        case 'evaluation_form':
            $evaluationController->showForm();
            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 'register_process':
        $registerController->register();
        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();
        exit();
        break;

    case 'get_unread_helpdesk_count':
        $helpdeskController->getUnreadCount();
        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 'evaluation_results':
        $evaluationController->showResults();
        break;

    case 'evaluation_submit':
        $evaluationController->submit();
        break;
    
    case 'evaluation_download':
        $evaluationController->downloadResults();
        exit();
        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 'delete_asset':
        $assetController->delete();
        break;
    case 'print_all_qrcodes': // New
        $assetController->printAllQRCodes();
        break;
    case 'upload_assets_excel':
        $assetController->uploadExcel();
        break;
    case 'mark_asset_repaired':
        $assetController->markAssetAsRepaired();
        break;
    case 'regenerate_qrs':
        $assetController->regenerateAllQRCodes();
        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 'sla_vendor_performance':
        $slaController->vendorPerformance();
        break;

    // Project Timeline Module
    case 'projects':
        $projectController->index();
        break;
    case 'project_create':
        $projectController->create();
        break;
    case 'project_store':
        $projectController->store();
        break;
    case 'project_show':
        $projectController->show();
        break;
    case 'project_store_task':
        $projectController->storeTask();
        break;
    case 'project_update_task_status':
        $projectController->updateTaskStatus();
        break;
    case 'project_update_status':
        $projectController->updateProjectStatus();
        break;
    case 'project_delete_task':
        $projectController->deleteTask();
        break;
    
    // Product Release Module
    case 'product_releases':
        $productReleaseController->index();
        break;
    case 'product_release_upload':
        $productReleaseController->upload();
        break;
    case 'product_release_delete':
        $productReleaseController->delete();
        break;

    // Room Temperature Monitoring Module
    case 'room_temperature':
        $roomTemperatureController->index();
        break;
    case 'room_temperature_history':
        $roomTemperatureController->history();
        break;
    case 'room_temperature_input':
        $roomTemperatureController->showInputForm();
        break;
    case 'room_temperature_add_reading':
        $roomTemperatureController->addReading();
        break;
    case 'room_temperature_public_report':
        $roomTemperatureController->publicMonthlyReport();
        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';
