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

$user = current_user();
$year = (int)($_GET['year'] ?? current_jalali_year());
$balance = get_user_balance($pdo, $user['id'], $year);

$dependents_enabled = get_setting($pdo, 'dependents_enabled', '1') === '1';
$dependents = [];
if ($dependents_enabled) {
    $stmt = $pdo->prepare("SELECT * FROM dependents WHERE user_id = ? AND status = 'approved' ORDER BY full_name");
    $stmt->execute([$user['id']]);
    $dependents = $stmt->fetchAll();
}
$relationLabels = ['spouse' => 'همسر', 'father' => 'پدر', 'mother' => 'مادر', 'child' => 'فرزند'];

function render_balance_bars_page($balance) {
    echo '<div class="row g-3 mb-2">';
    foreach ($balance['rows'] as $r) {
        if (!empty($r['blocked_reason'])) {
            echo '<div class="col-md-6"><div class="balance-item blocked"><div class="balance-title">' . htmlspecialchars($r['name']) . '</div>'
               . '<div class="small">غیرفعال برای شما: ' . htmlspecialchars($r['blocked_reason']) . '</div></div></div>';
            continue;
        }
        $ratio = $r['max_amount'] > 0 ? $r['remaining'] / $r['max_amount'] : 0;
        $pct = max(2, min(100, round($ratio * 100)));
        $lowCls = $ratio < 0.15 ? ' low' : '';
        echo '<div class="col-md-6"><div class="balance-item' . $lowCls . '">'
           . '<div class="balance-title">' . htmlspecialchars($r['name']) . '</div>'
           . '<div class="balance-figures"><span>مانده: ' . format_amount($r['remaining']) . '</span><span>سقف: ' . format_amount($r['max_amount']) . '</span></div>'
           . '<div class="balance-track"><div class="balance-fill" style="width:' . $pct . '%"></div></div>'
           . '</div></div>';
    }
    echo '</div>';

    if (!empty($balance['caps'])) {
        echo '<div class="small text-muted mb-2 mt-1">سقف‌های ترکیبی:</div><div class="row g-3">';
        foreach ($balance['caps'] as $c) {
            $ratio = $c['max_amount'] > 0 ? $c['remaining'] / $c['max_amount'] : 0;
            $pct = max(2, min(100, round($ratio * 100)));
            $lowCls = $ratio < 0.15 ? ' low' : '';
            echo '<div class="col-md-6"><div class="balance-item' . $lowCls . '">'
               . '<div class="balance-title">' . htmlspecialchars($c['name']) . '</div>'
               . '<div class="balance-figures"><span>مانده: ' . format_amount($c['remaining']) . '</span><span>سقف: ' . format_amount($c['max_amount']) . '</span></div>'
               . '<div class="balance-track"><div class="balance-fill" style="width:' . $pct . '%"></div></div>'
               . '</div></div>';
        }
        echo '</div>';
    }
}

$page_title = 'مانده حساب';
include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <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>

<?php if ($balance['proration_ratio'] < 1): ?>
  <div class="alert alert-info small">
    با توجه به تاریخ استخدام شما در سال جاری، سقف شما امسال معادل <?= fa_num(round($balance['proration_ratio'] * 100)) ?>٪ سقف کامل محاسبه شده است.
  </div>
<?php endif; ?>

<div class="accordion" id="balanceAccordion">
  <div class="accordion-item">
    <h2 class="accordion-header">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#balSelf">مانده خودم</button>
    </h2>
    <div id="balSelf" class="accordion-collapse collapse" data-bs-parent="#balanceAccordion">
      <div class="accordion-body"><?php render_balance_bars_page($balance); ?></div>
    </div>
  </div>

  <?php foreach ($dependents as $i => $dep): ?>
    <?php $depBalance = get_user_balance($pdo, $user['id'], $year, $dep['id']); ?>
    <div class="accordion-item">
      <h2 class="accordion-header">
        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#balDep<?= $i ?>">
          مانده <?= htmlspecialchars($dep['full_name']) ?> (<?= $relationLabels[$dep['relation']] ?? '' ?>)
        </button>
      </h2>
      <div id="balDep<?= $i ?>" class="accordion-collapse collapse" data-bs-parent="#balanceAccordion">
        <div class="accordion-body"><?php render_balance_bars_page($depBalance); ?></div>
      </div>
    </div>
  <?php endforeach; ?>
</div>

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