<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }

    $database = new Database();
    $db = $database->getConnection();

    $roles = [];
    $departments = [];

    $rolesQuery = "SELECT * FROM `user_roles` WHERE `role_name` NOT IN ('hod', 'admin', 'superadmin');";

    $rolesStmt = $db->prepare($rolesQuery);
    $rolesStmt->execute();
    $rolesResult = $rolesStmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($rolesResult) > 0) {
        $roles = $rolesResult;
    }

    $departmentsQuery = "SELECT * FROM `departments`";

    $departmentsStmt = $db->prepare($departmentsQuery);
    $departmentsStmt->execute();
    $departmentsResult = $departmentsStmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($departmentsResult) > 0) {
        $departments = $departmentsResult;
    }

    $result = [
        "roles" => $roles,
        "departments" => $departments
    ];

    Helpers::sendResponse(true, '', $result, 0);
} catch (PDOException $e) {
    ErrorLogger::logAuthError($e, $data->username ?? 'unknown');
    Helpers::sendResponse(false, 'An error occurred during login', null, 500);
} catch (Exception $e) {
    ErrorLogger::logAuthError($e, $data->username ?? 'unknown');
    Helpers::sendResponse(false, 'An unexpected error occurred', null, 500);
}
