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

$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_claim') {
    verify_csrf();
    $claim_id = (int)$_POST['claim_id'];
    delete_claim($pdo, $claim_id);
    log_activity($pdo, 'delete_claim', 'حذف درخواست تستی/اشتباه', $claim_id);
    $success = 'درخواست حذف شد.';
}

$status_filter = $_GET['status'] ?? '';
$year_filter = $_GET['year'] ?? '';
$search = trim($_GET['q'] ?? '');

$sql = "
    SELECT c.*, r.name AS row_name, u.full_name, u.personnel_code
    FROM claims c
    JOIN insurance_rows r ON r.id = c.row_id
    JOIN users u ON u.id = c.user_id
    WHERE 1=1
";
$params = [];

if ($status_filter !== '') {
    $sql .= " AND c.status = ?";
    $params[] = $status_filter;
}
if ($year_filter !== '') {
    $sql .= " AND c.claim_year = ?";
    $params[] = (int)$year_filter;
}
if ($search !== '') {
    $sql .= " AND u.full_name LIKE ?";
    $params[] = '%' . $search . '%';
}
$sql .= " ORDER BY c.created_at DESC LIMIT 300";

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

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

<h4 class="mb-4">همه درخواست‌ها</h4>

<?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

<form method="get" class="row g-2 mb-4">
  <div class="col-md-3">
    <select name="status" class="form-select">
      <option value="">همه وضعیت‌ها</option>
      <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>در انتظار بررسی</option>
      <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>تایید شده</option>
      <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>رد شده</option>
      <option value="paid" <?= $status_filter === 'paid' ? 'selected' : '' ?>>پرداخت شده</option>
    </select>
  </div>
  <div class="col-md-2">
    <input type="number" name="year" class="form-control" placeholder="سال شمسی" value="<?= htmlspecialchars($year_filter) ?>">
  </div>
  <div class="col-md-3">
    <input type="text" name="q" class="form-control" placeholder="جستجوی نام کارمند" value="<?= htmlspecialchars($search) ?>">
  </div>
  <div class="col-md-2">
    <button class="btn btn-outline-primary w-100">فیلتر</button>
  </div>
</form>

<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>
    </tr>
  </thead>
  <tbody>
    <?php if (!$claims): ?>
      <tr><td colspan="8">
        <div class="empty-state">
          <img src="<?= base_url('assets/img/no-results.svg') ?>" alt="">
          <div>موردی با این مشخصات یافت نشد.</div>
        </div>
      </td></tr>
    <?php endif; ?>
    <?php foreach ($claims as $c): ?>
      <tr>
        <td><?= to_jalali_string($c['created_at']) ?></td>
        <td><?= htmlspecialchars($c['full_name']) ?><?= $c['is_dependent'] ? ' <span class="badge bg-secondary">فرد تبعی</span>' : '' ?></td>
        <td><?= htmlspecialchars($c['row_name']) ?></td>
        <td><?= format_amount($c['amount_requested']) ?></td>
        <td><?= $c['amount_approved'] !== null ? format_amount($c['amount_approved']) : '-' ?></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></td>
        <td>
          <a href="review_claim.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-outline-primary">مشاهده</a>
          <?php if (in_array($c['status'], ['approved','paid'])): ?>
            <a href="print_form.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-outline-secondary">فرم چاپی</a>
          <?php endif; ?>
          <form method="post" class="d-inline">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="delete_claim">
            <input type="hidden" name="claim_id" value="<?= $c['id'] ?>">
            <button class="btn btn-sm btn-outline-danger" onclick="return confirm('این درخواست و مدارک آن برای همیشه حذف شود؟')">حذف</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>

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