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

$user = current_user();
$year = (int)($_GET['year'] ?? current_jalali_year());
$statusFilter = $_GET['status'] ?? '';

$sql = "
    SELECT c.*, r.name AS row_name, d.full_name AS dependent_name
    FROM claims c
    JOIN insurance_rows r ON r.id = c.row_id
    LEFT JOIN dependents d ON d.id = c.dependent_id
    WHERE c.user_id = ? AND c.claim_year = ?
";
$params = [$user['id'], $year];
if ($statusFilter !== '' && in_array($statusFilter, ['pending', 'approved', 'rejected', 'paid', 'needs_correction'])) {
    $sql .= " AND c.status = ?";
    $params[] = $statusFilter;
}
$sql .= " ORDER BY c.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$claims = $stmt->fetchAll();

$doc_stmt = $pdo->prepare("SELECT * FROM claim_documents WHERE claim_id = ?");

$page_title = 'تاریخچه درخواست‌ها';
include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <h4 class="mb-0">تاریخچه درخواست‌ها</h4>
  <form class="d-flex gap-2" method="get">
    <select name="status" class="form-select form-select-sm" style="width:170px" onchange="this.form.submit()">
      <option value="">همه وضعیت‌ها</option>
      <option value="pending" <?= $statusFilter === 'pending' ? 'selected' : '' ?>>در انتظار بررسی</option>
      <option value="needs_correction" <?= $statusFilter === 'needs_correction' ? 'selected' : '' ?>>نیاز به اصلاح</option>
      <option value="approved" <?= $statusFilter === 'approved' ? 'selected' : '' ?>>تایید شده</option>
      <option value="paid" <?= $statusFilter === 'paid' ? 'selected' : '' ?>>پرداخت شده</option>
      <option value="rejected" <?= $statusFilter === 'rejected' ? 'selected' : '' ?>>رد شده</option>
    </select>
    <input type="number" name="year" value="<?= $year ?>" class="form-control form-control-sm" style="width:100px">
    <button class="btn btn-sm btn-outline-secondary">نمایش</button>
  </form>
</div>

<div class="table-responsive">
<table class="table table-bordered align-middle">
  <thead class="table-light">
    <tr>
      <th>تاریخ ثبت</th><th>برای</th><th>ردیف</th><th>مرکز درمانی</th><th>مبلغ درخواستی</th><th>مبلغ تایید‌شده</th><th>فرانشیز</th><th>مبلغ قابل پرداخت</th><th>وضعیت</th><th>مدارک</th><th>یادداشت بررسی</th>
    </tr>
  </thead>
  <tbody>
    <?php if (!$claims): ?>
      <tr><td colspan="11">
        <div class="empty-state">
          <img src="<?= base_url('assets/img/empty-state.svg') ?>" alt="">
          <div>درخواستی با این مشخصات ثبت نشده است.</div>
        </div>
      </td></tr>
    <?php endif; ?>
    <?php foreach ($claims as $c): ?>
      <?php $doc_stmt->execute([$c['id']]); $docs = $doc_stmt->fetchAll(); ?>
      <tr>
        <td><?= to_jalali_string($c['created_at']) ?></td>
        <td><?= $c['is_dependent'] ? htmlspecialchars($c['dependent_name']) : 'خودم' ?></td>
        <td><?= htmlspecialchars($c['row_name']) ?></td>
        <td class="small"><?= htmlspecialchars($c['medical_center'] ?? '-') ?></td>
        <td><?= format_amount($c['amount_requested']) ?></td>
        <td><?= $c['amount_approved'] !== null ? format_amount($c['amount_approved']) : '-' ?>
            <?php if ($c['cap_limited']): ?><span class="badge bg-warning text-dark">محدود به سقف</span><?php endif; ?>
        </td>
        <td class="small"><?= $c['franchise_amount'] ? format_amount($c['franchise_amount']) . " (" . fa_num($c['franchise_percent']) . "٪)" : '-' ?></td>
        <td><?= $c['payable_amount'] !== null ? format_amount($c['payable_amount']) : '-' ?></td>
        <td><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 d-block mt-1">ویرایش و ارسال مجدد</a>
          <?php endif; ?>
        </td>
        <td>
          <?php foreach ($docs as $d): ?>
            <a href="<?= base_url('download.php?id=' . $d['id']) ?>" target="_blank" class="d-block small"><?= icon('paperclip') ?> <?= htmlspecialchars($d['item_label'] ?: $d['original_name']) ?></a>
          <?php endforeach; ?>
        </td>
        <td class="small text-muted"><?= htmlspecialchars($c['admin_note'] ?? '') ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>

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