<?php
require_once __DIR__ . '/../includes/functions.php';
require_role('admin');

$year = (int)($_GET['year'] ?? current_jalali_year());
$employees = $pdo->query("SELECT * FROM users WHERE role = 'employee' ORDER BY full_name")->fetchAll();
$rows = $pdo->query("SELECT * FROM insurance_rows WHERE is_active = 1 ORDER BY sort_order")->fetchAll();
$dep_stmt = $pdo->prepare("SELECT * FROM dependents WHERE user_id = ? AND status = 'approved' ORDER BY full_name");

// ساخت لیست ستون‌ها: هر کارمند، بلافاصله بعدش افراد تبعی خودش
$columns = [];
foreach ($employees as $emp) {
    $balance = get_user_balance($pdo, $emp['id'], $year);
    $byRow = [];
    foreach ($balance['rows'] as $b) { $byRow[$b['id']] = $b; }
    $columns[] = [
        'name' => $emp['full_name'],
        'parent' => '-',
        'byRow' => $byRow,
    ];

    $dep_stmt->execute([$emp['id']]);
    $deps = $dep_stmt->fetchAll();
    foreach ($deps as $dep) {
        $depBalance = get_user_balance($pdo, $emp['id'], $year, $dep['id']);
        $byRowDep = [];
        foreach ($depBalance['rows'] as $b) { $byRowDep[$b['id']] = $b; }
        $columns[] = [
            'name' => $dep['full_name'],
            'parent' => $emp['full_name'],
            'byRow' => $byRowDep,
        ];
    }
}

$page_title = 'گزارش مانده پرسنل';
include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h4 class="mb-0">گزارش مانده حساب پرسنل - سال <?= fa_num($year) ?></h4>
  <form class="d-flex" method="get">
    <input type="number" name="year" value="<?= $year ?>" class="form-control form-control-sm me-2" style="width:100px">
    <button class="btn btn-sm btn-outline-secondary">نمایش</button>
  </form>
</div>

<div class="sticky-table-wrap border rounded" id="reportTableWrap">
<table class="table table-bordered table-sm align-middle text-center mb-0" id="reportTable">
  <thead>
    <tr>
      <th rowspan="2" style="min-width:220px;">ردیف درمانی</th>
      <?php foreach ($columns as $col): ?>
        <th style="min-width:130px;"><?= htmlspecialchars($col['name']) ?></th>
      <?php endforeach; ?>
    </tr>
    <tr class="report-sub-header">
      <?php foreach ($columns as $col): ?>
        <th class="small text-muted fw-normal"><?= htmlspecialchars($col['parent']) ?></th>
      <?php endforeach; ?>
    </tr>
  </thead>
  <tbody>
    <?php if (!$rows || !$columns): ?>
      <tr><td colspan="<?= count($columns) + 1 ?>">
        <div class="empty-state">
          <img src="<?= base_url('assets/img/no-results.svg') ?>" alt="">
          <div>داده‌ای برای نمایش وجود ندارد.</div>
        </div>
      </td></tr>
    <?php endif; ?>
    <?php foreach ($rows as $r): ?>
      <tr>
        <th class="text-start small"><?= htmlspecialchars($r['name']) ?></th>
        <?php foreach ($columns as $col): ?>
          <?php $b = $col['byRow'][$r['id']] ?? null; ?>
          <td class="small">
            <?php if ($b): ?>
              <div class="text-muted" style="font-size:0.75rem">مصرف: <?= fa_num(number_format($b['used'])) ?></div>
              <div class="fw-medium">مانده: <?= fa_num(number_format($b['remaining'])) ?></div>
            <?php else: ?> - <?php endif; ?>
          </td>
        <?php endforeach; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>
<p class="text-muted small mt-2">مبالغ به ریال هستند. ردیف اول (اسم فرد)، ردیف دوم (اسم نفر اصلی — برای خودِ کارمند خط تیره)، و ستون اول (اسم ردیف درمانی) هنگام اسکرول ثابت می‌مانند.</p>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var table = document.getElementById('reportTable');
    if (!table) return;
    var firstRow = table.querySelector('thead tr:first-child');
    var secondRow = table.querySelector('thead tr.report-sub-header');
    if (!firstRow || !secondRow) return;
    var h = firstRow.getBoundingClientRect().height;
    secondRow.querySelectorAll('th').forEach(function (th) {
        th.style.top = h + 'px';
    });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
