<?php
require_once __DIR__ . '/auth.php';
function normalize_link(?string $link = null): string { $link = $link ?? parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?? ''; $link = ltrim($link, '/'); return $link === '' || $link === 'index.php' ? 'dashboard.php' : $link; }
function acl_for(?string $link = null): array
{
    global $con;
    $user = current_user();
    $roleId = (int)($user['role_id'] ?? 0);
    $link = normalize_link($link);

    if ($roleId === 1 && $link === 'dashboard.php') {
        return ['title'=>'Dashboard','can_view'=>true,'can_add'=>true,'can_edit'=>true,'can_delete'=>true];
    }

    // Pages moved into modules/hrms may still request their original relative
    // ACL path. Match both forms so old URLs and new module URLs share access.
    $alternateLink = $link;
    if (preg_match('#^modules/hrms/(.+)$#i', $link, $match)) {
        $alternateLink = $match[1];
    } elseif (preg_match('#^(attendance|leave|payroll|reports|masters|organization|salary-config|payroll-config|operations|form16|reset-data)/#i', $link)) {
        $alternateLink = 'modules/hrms/' . $link;
    }

    $stmt = $con->prepare(
        'SELECT m.id, m.menu_name, m.remarks, rm.can_view, rm.can_add, rm.can_edit, rm.can_delete
         FROM jos_admin_menus m
         LEFT JOIN jos_admin_rolemenus rm
           ON rm.menu_id=m.id AND rm.role_id=? AND rm.status=1
         WHERE (m.menu_link IN (?,?) OR m.url IN (?,?))
           AND m.status=1
         LIMIT 1'
    );
    $stmt->bind_param('issss', $roleId, $link, $alternateLink, $link, $alternateLink);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$row) {
        return ['title'=>'','can_view'=>false,'can_add'=>false,'can_edit'=>false,'can_delete'=>false];
    }

    return [
        'title'=>$row['menu_name'],
        'remark'=>$row['remarks'] ?? '',
        'can_view'=>!empty($row['can_view']),
        'can_add'=>!empty($row['can_add']),
        'can_edit'=>!empty($row['can_edit']),
        'can_delete'=>!empty($row['can_delete'])
    ];
}
function require_acl(string $permission = 'can_view', ?string $link = null): array { $acl = acl_for($link); if (empty($acl[$permission])) { http_response_code(403); exit('Access denied.'); } return $acl; }