<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin');
$db = Database::getInstance();
$page = 'Menu Rights';

// Master list of modules grouped by section
$moduleGroups = [
    'Employees'   => ['employees.list'=>'Employee List','employees.create'=>'Add Employee','employees.transfer'=>'Transfer','employees.assign'=>'Assignment','employees.accounts'=>'Bank Accounts','employees.profile'=>'Profile','employees.orgchart'=>'Org Chart'],
    'Attendance'  => ['attendance.marking'=>'Attendance Marking','attendance.muster'=>'Muster','attendance.timesheet'=>'Timesheet','attendance.my_attendance'=>'My Attendance'],
    'Leave'       => ['leave.index'=>'Leave Management','leave.my_leaves'=>'My Leaves'],
    'Payroll'     => ['payroll.calculate'=>'Process Payroll','payroll.paycodes'=>'Pay Codes','payroll.arrears'=>'Arrears','payroll.bonus'=>'Bonus','payroll.gratuity'=>'Gratuity','payroll.lta'=>'LTA','payroll.leave_encashment'=>'Leave Encashment','payroll.post_salary'=>'Post Salary','payroll.disbursement'=>'Disbursement'],
    'TDS & Tax'   => ['tds.calculate'=>'TDS Calculation','tds.tax_slab'=>'Tax Slab','tds.tds_heads'=>'TDS Heads','tds.adb_rules'=>'ADB Rules','tds.investment'=>'Investment Declaration','tds.monthly_chart'=>'TDS Monthly Chart'],
    'Statutory'   => ['statutory.pf'=>'PF','statutory.esi'=>'ESI','statutory.pt'=>'Professional Tax'],
    'HR Ops'      => ['recruitment.index'=>'Recruitment','appraisal.index'=>'Appraisal','training.index'=>'Training','expense.index'=>'Expense Booking','notice.index'=>'Notice Board','advance.index'=>'Advance','separation.index'=>'Separation','support.index'=>'Support'],
    'Reports'     => ['reports.hr_reports'=>'HR Reports','reports.statutory'=>'Statutory Reports','reports.earning_deduction'=>'Earnings & Deductions','reports.custom'=>'Custom Report','reports.summary'=>'Summary Report','reports.letter'=>'Letter Generation'],
    'Configuration'=> ['configuration.departments'=>'Departments & Masters','configuration.menu_rights'=>'Menu Rights','configuration.pf_esi_setup'=>'PF/ESI Setup','configuration.gratuity_setup'=>'Gratuity Setup','configuration.holidays'=>'Holiday Calendar'],
];

$roles = ['superadmin','admin','management','hod','supervisor','hr','manager','employee'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $role = post('role');
    if (!in_array($role, $roles)) { setFlash('error','Invalid role.'); header('Location: '.BASE_URL.'/modules/configuration/menu_rights.php'); exit; }

    $perms = $_POST['perm'] ?? []; // perms[module][can_view/add/edit/delete/approve] = 1

    foreach ($moduleGroups as $group => $mods) {
        foreach ($mods as $modKey => $modLabel) {
            $p = $perms[$modKey] ?? [];
            $data = [
                'role'        => $role,
                'module'      => $modKey,
                'can_view'    => isset($p['view'])    ? 1 : 0,
                'can_add'     => isset($p['add'])     ? 1 : 0,
                'can_edit'    => isset($p['edit'])    ? 1 : 0,
                'can_delete'  => isset($p['delete'])  ? 1 : 0,
                'can_approve' => isset($p['approve']) ? 1 : 0,
            ];
            $existing = $db->fetchOne("SELECT id FROM menu_rights WHERE role=? AND module=?", [$role, $modKey]);
            if ($existing) {
                $db->execute("UPDATE menu_rights SET can_view=?,can_add=?,can_edit=?,can_delete=?,can_approve=? WHERE id=?",
                    [$data['can_view'],$data['can_add'],$data['can_edit'],$data['can_delete'],$data['can_approve'],$existing['id']]);
            } else {
                $db->execute("INSERT INTO menu_rights (role,module,can_view,can_add,can_edit,can_delete,can_approve) VALUES (?,?,?,?,?,?,?)",
                    [$role,$modKey,$data['can_view'],$data['can_add'],$data['can_edit'],$data['can_delete'],$data['can_approve']]);
            }
        }
    }
    setFlash('success', 'Menu rights updated for role: ' . ucfirst($role));
    header('Location: '.BASE_URL.'/modules/configuration/menu_rights.php?role='.$role); exit;
}

$selRole = $_GET['role'] ?? 'employee';
if (!in_array($selRole, $roles)) $selRole = 'employee';

$existingPerms = $db->fetchAll("SELECT * FROM menu_rights WHERE role=?", [$selRole]);
$permMap = [];
foreach ($existingPerms as $p) $permMap[$p['module']] = $p;

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <div class="d-flex align-items-center gap-2">
    <i class="ti ti-shield-lock" style="font-size:20px;color:var(--pc-brand)"></i>
    <span class="fw-semibold">Select Role to Configure</span>
    <div class="ms-2 d-flex gap-1">
      <?php foreach($roles as $r): ?>
      <a href="?role=<?=$r?>" class="btn btn-sm <?=$selRole===$r?'btn-pc':'btn-outline-secondary'?>"><?=ucfirst($r)?></a>
      <?php endforeach; ?>
    </div>
    <?php if($selRole==='superadmin'): ?>
    <span class="badge ms-auto" style="background:var(--pc-amber-bg);color:var(--pc-amber)">Superadmin has full access by default — changes here are advisory only</span>
    <?php endif; ?>
  </div>
</div>

<form method="POST">
  <?=csrfField()?><input type="hidden" name="role" value="<?=$selRole?>">
  <?php foreach($moduleGroups as $group => $mods): ?>
  <div class="pc-card mb-3">
    <div class="pc-card-title"><i class="ti ti-folder me-2"></i><?=$group?></div>
    <div class="pc-table-wrap">
      <table class="pc-table">
        <thead><tr><th>Module</th><th style="text-align:center">View</th><th style="text-align:center">Add</th><th style="text-align:center">Edit</th><th style="text-align:center">Delete</th><th style="text-align:center">Approve</th></tr></thead>
        <tbody>
        <?php foreach($mods as $modKey => $modLabel):
          $p = $permMap[$modKey] ?? ['can_view'=>0,'can_add'=>0,'can_edit'=>0,'can_delete'=>0,'can_approve'=>0];
        ?>
        <tr>
          <td class="fw-semibold"><?=clean($modLabel)?></td>
          <?php foreach(['view'=>'can_view','add'=>'can_add','edit'=>'can_edit','delete'=>'can_delete','approve'=>'can_approve'] as $key=>$col): ?>
          <td style="text-align:center">
            <input type="checkbox" class="form-check-input" name="perm[<?=$modKey?>][<?=$key?>]" value="1" <?=$p[$col]?'checked':''?>>
          </td>
          <?php endforeach; ?>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php endforeach; ?>

  <div class="pc-card sticky-bottom" style="position:sticky;bottom:0;z-index:10">
    <div class="d-flex justify-content-between align-items-center">
      <span class="text-muted small">Configuring permissions for role: <strong class="text-brand"><?=ucfirst($selRole)?></strong></span>
      <button class="btn btn-pc"><i class="ti ti-device-floppy me-1"></i>Save Menu Rights</button>
    </div>
  </div>
</form>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
