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

$user = current_user();
$balance = get_user_balance($pdo, $user['id']);

$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' => 'فرزند'];

$stmt = $pdo->prepare("
    SELECT c.*, r.name AS row_name
    FROM claims c JOIN insurance_rows r ON r.id = c.row_id
    WHERE c.user_id = ?
    ORDER BY c.created_at DESC
    LIMIT 8
");
$stmt->execute([$user['id']]);
$recent = $stmt->fetchAll();

// آمار سریع
$stmt = $pdo->prepare("SELECT COUNT(*) FROM claims WHERE user_id = ? AND status = 'pending'");
$stmt->execute([$user['id']]);
$pendingCount = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM claims WHERE user_id = ? AND status = 'needs_correction'");
$stmt->execute([$user['id']]);
$correctionCount = (int)$stmt->fetchColumn();

$totalRemaining = 0;
foreach ($balance['rows'] as $r) {
    if (empty($r['blocked_reason'])) $totalRemaining += $r['remaining'];
}

function render_balance_bars($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="welcome-banner">
  <div class="welcome-text">
    <h4>سلام، <?= htmlspecialchars($user['full_name']) ?></h4>
    <p>خلاصه‌ی وضعیت بیمه تکمیلی شما</p>
  </div>
  <img src="<?= base_url('assets/img/welcome-illustration.svg') ?>" class="welcome-illustration" alt="">
</div>

<div class="row g-3 mb-4">
  <div class="col-6 col-lg-3">
    <a href="balance.php" class="text-decoration-none text-body">
      <div class="stat-card">
        <div class="stat-icon" style="background: var(--accent-teal-bg); color: var(--primary);"><?= icon('coin') ?></div>
        <div><div class="stat-value"><?= format_amount($totalRemaining) ?></div><div class="stat-label">مجموع دریافت شده</div></div>
      </div>
    </a>
  </div>
  <div class="col-6 col-lg-3">
    <a href="history.php?status=pending" class="text-decoration-none text-body">
      <div class="stat-card">
        <div class="stat-icon" style="background: var(--accent-blue-bg); color: var(--accent-blue);"><?= icon('clock') ?></div>
        <div><div class="stat-value"><?= fa_num($pendingCount) ?></div><div class="stat-label">در انتظار بررسی</div></div>
      </div>
    </a>
  </div>
  <div class="col-6 col-lg-3">
    <a href="history.php?status=needs_correction" class="text-decoration-none text-body">
      <div class="stat-card">
        <div class="stat-icon" style="background: var(--accent-yellow-bg); color: var(--accent-yellow);"><?= icon('file-check') ?></div>
        <div><div class="stat-value"><?= fa_num($correctionCount) ?></div><div class="stat-label">نیاز به اصلاح</div></div>
      </div>
    </a>
  </div>
  <div class="col-6 col-lg-3">
    <a href="dependents.php" class="text-decoration-none text-body">
      <div class="stat-card">
        <div class="stat-icon" style="background: var(--accent-purple-bg); color: var(--accent-purple);"><?= icon('family') ?></div>
        <div><div class="stat-value"><?= fa_num(count($dependents)) ?></div><div class="stat-label">افراد تبعی تایید‌شده</div></div>
      </div>
    </a>
  </div>
</div>

<div class="row g-4">
  <div class="col-lg-7">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h6 class="mb-0 fw-heading">درخواست‌های اخیر</h6>
      <a href="submit_claim.php" class="btn btn-primary btn-sm"><?= icon('plus-circle') ?> ثبت درخواست جدید</a>
    </div>
    <div class="card p-3">
      <?php if (!$recent): ?>
        <div class="empty-state">
          <img src="<?= base_url('assets/img/empty-state.svg') ?>" alt="">
          <div>هنوز درخواستی ثبت نکرده‌اید.</div>
        </div>
      <?php else: ?>
        <?php foreach ($recent as $c): ?>
          <div class="claim-item">
            <div class="claim-icon"><?= icon('paperclip') ?></div>
            <div class="claim-main">
              <div class="claim-title"><?= htmlspecialchars($c['row_name']) ?></div>
              <div class="claim-meta">
                <?= to_jalali_string($c['created_at']) ?> · <?= $c['is_dependent'] ? 'فرد تبعی' : 'خودم' ?>
                <span class="badge <?= status_badge_class($c['status']) ?>"><?= status_label($c['status']) ?></span>
                <?php if ($c['status'] === 'needs_correction'): ?>
                  <a href="edit_claim.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-warning py-0 px-2">اصلاح</a>
                <?php endif; ?>
              </div>
            </div>
            <div class="claim-amount"><?= format_amount($c['payable_amount'] ?? $c['amount_requested']) ?></div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
    <a href="history.php" class="btn btn-outline-primary btn-sm mt-3">مشاهده کل تاریخچه</a>
  </div>

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

    <h6 class="mb-2 fw-heading">دریافت شده — سال <?= fa_num($balance['year']) ?></h6>
    <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($balance); ?></div>
        </div>
      </div>

      <?php foreach ($dependents as $i => $dep): ?>
        <?php $depBalance = get_user_balance($pdo, $user['id'], null, $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($depBalance); ?></div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

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