<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management','manager');
$db   = Database::getInstance();
$page = 'Muster & Leave Report';

[$eOrg, $eOrgP] = orgScopeClause($db, 'e.company_id');
$type = get('type') ?: 'leave_history';

$reports = [
    'leave_history' => 'Leave History',
    'report_wizard' => 'Report Wizard',
    'leave_encash'  => 'Leave Encash',
    'leave_tracker' => 'Leave Tracker',
    'compoff'       => 'Comp-Off',
];
if (!isset($reports[$type])) $type = 'leave_history';

$cols = []; $rows = [];

// ── Common filters for the wizard / history views ────────────
$month = cleanInt($_GET['month'] ?? date('n'));
$year  = cleanInt($_GET['year']  ?? date('Y'));
$dept  = cleanInt($_GET['dept']  ?? 0);
$deptFilter = $dept ? "AND e.department_id=$dept" : '';
$depts = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");

switch ($type) {

    case 'leave_history':
        $cols = ['Emp Code','Name','Leave Type','From','To','Days','Status','Reason'];
        $rows = $db->fetchAll(
            "SELECT e.employee_id, CONCAT(e.first_name,' ',e.last_name) AS name, lt.name AS leave_type,
                    la.from_date, la.to_date, la.days, la.status, la.reason
               FROM leave_applications la
               JOIN employees e ON e.id=la.employee_id
               JOIN leave_types lt ON lt.id=la.leave_type_id
              WHERE MONTH(la.from_date)=? AND YEAR(la.from_date)=? AND $eOrg $deptFilter
              ORDER BY la.from_date DESC",
            array_merge([$month, $year], $eOrgP)
        );
        break;

    case 'report_wizard':
        // Simple step-through: pick month/year/department -> get a
        // combined attendance + leave snapshot for that scope.
        $cols = ['Emp Code','Name','Department','Present','Absent','Leave','Late','LOP'];
        $rows = $db->fetchAll(
            "SELECT e.employee_id, CONCAT(e.first_name,' ',e.last_name) AS name, d.name AS dept,
                    COALESCE(ms.present_days,0) AS present, COALESCE(ms.absent_days,0) AS absent,
                    COALESCE(ms.leave_days,0) AS leave_days, COALESCE(ms.late_count,0) AS late,
                    COALESCE(ms.lop_days,0) AS lop
               FROM employees e
          LEFT JOIN departments d ON d.id=e.department_id
          LEFT JOIN muster_summary ms ON ms.employee_id=e.id AND ms.month=? AND ms.year=?
              WHERE e.status='active' AND $eOrg $deptFilter
              ORDER BY e.first_name",
            array_merge([$month, $year], $eOrgP)
        );
        break;

    case 'leave_encash':
        $cols = ['Date','Emp Code','Name','Leave Type','Days','Amount','Processed By'];
        $rows = $db->fetchAll(
            "SELECT lel.created_at, e.employee_id, CONCAT(e.first_name,' ',e.last_name) AS name,
                    lt.name AS leave_type, lel.days, lel.amount, u.username AS processed_by
               FROM leave_encashment_log lel
               JOIN employees e ON e.id=lel.employee_id
               JOIN leave_types lt ON lt.id=lel.leave_type_id
          LEFT JOIN users u ON u.id=lel.processed_by
              WHERE $eOrg
              ORDER BY lel.created_at DESC LIMIT 300",
            $eOrgP
        );
        break;

    case 'leave_tracker':
        $cols = ['Emp Code','Name','Leave Type','Allocated','Used','Carry Forward','Available'];
        $rows = $db->fetchAll(
            "SELECT e.employee_id, CONCAT(e.first_name,' ',e.last_name) AS name, lt.name AS leave_type,
                    lb.allocated, lb.used, COALESCE(lb.carry_forward,0) AS carry_forward,
                    (lb.allocated + COALESCE(lb.carry_forward,0) - lb.used) AS available
               FROM employee_leave_balance lb
               JOIN employees e ON e.id=lb.employee_id
               JOIN leave_types lt ON lt.id=lb.leave_type_id
              WHERE lb.year=? AND e.status='active' AND $eOrg $deptFilter
              ORDER BY e.first_name, lt.name",
            array_merge([$year], $eOrgP)
        );
        break;

    case 'compoff':
        $cols = ['Emp Code','Name','Worked Date','Availed Date','Status'];
        $rows = $db->fetchAll(
            "SELECT e.employee_id, CONCAT(e.first_name,' ',e.last_name) AS name,
                    co.worked_date, co.availed_date, co.status
               FROM comp_off co
               JOIN employees e ON e.id=co.employee_id
              WHERE $eOrg
              ORDER BY co.worked_date DESC LIMIT 300",
            $eOrgP
        );
        break;
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-3">
    <div class="pc-card p-2">
      <div class="pc-card-title">Muster &amp; Leave Reports</div>
      <div class="list-group list-group-flush">
        <a href="<?=BASE_URL?>/modules/attendance/muster_report.php" class="list-group-item list-group-item-action small">Muster Roll</a>
        <?php foreach ($reports as $key => $label): ?>
        <a href="?type=<?= $key ?>" class="list-group-item list-group-item-action small <?= $type===$key?'active':'' ?>"><?= clean($label) ?></a>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  <div class="col-md-9">
    <?php if (in_array($type, ['leave_history','report_wizard','leave_tracker'])): ?>
    <div class="pc-card mb-3">
      <form method="GET" class="d-flex gap-2 flex-wrap align-items-end">
        <input type="hidden" name="type" value="<?= $type ?>">
        <div><label class="pc-label">Month</label>
          <select name="month" class="form-select form-select-sm">
            <?php for ($m=1;$m<=12;$m++): ?><option value="<?=$m?>" <?=$month==$m?'selected':''?>><?=monthName($m)?></option><?php endfor; ?>
          </select></div>
        <div><label class="pc-label">Year</label>
          <input type="number" name="year" value="<?=$year?>" class="form-control form-control-sm" style="width:90px"></div>
        <div><label class="pc-label">Department</label>
          <select name="dept" class="form-select form-select-sm">
            <option value="">All</option>
            <?php foreach($depts as $d): ?><option value="<?=$d['id']?>" <?=$dept==$d['id']?'selected':''?>><?=clean($d['name'])?></option><?php endforeach; ?>
          </select></div>
        <button class="btn btn-pc btn-sm">Apply</button>
      </form>
    </div>
    <?php endif; ?>

    <div class="pc-card">
      <div class="pc-card-title d-flex justify-content-between align-items-center">
        <span><?= clean($reports[$type]) ?> (<?= count($rows) ?>)</span>
        <a href="#" onclick="window.print();return false;" class="small"><i class="ti ti-printer me-1"></i>Print</a>
      </div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><?php foreach ($cols as $c): ?><th><?= clean($c) ?></th><?php endforeach; ?></tr></thead>
          <tbody>
          <?php foreach ($rows as $r): ?>
            <tr><?php foreach ($r as $k => $v): if (is_numeric($k)) continue; ?><td><?= clean(is_null($v) ? '—' : $v) ?></td><?php endforeach; ?></tr>
          <?php endforeach; ?>
          <?php if (!$rows): ?><tr><td colspan="10" class="text-center text-muted py-4">No records found</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
