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

$admin = current_user();
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $dependent_id = (int)($_POST['dependent_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $note = trim($_POST['admin_note'] ?? '');

    if ($action === 'approve') {
        $stmt = $pdo->prepare("UPDATE dependents SET status = 'approved', admin_note = ?, reviewed_at = NOW(), reviewed_by = ? WHERE id = ?");
        $stmt->execute([$note ?: null, $admin['id'], $dependent_id]);
        log_activity($pdo, 'approve_dependent', $note, null);
        $success = 'فرد تبعی تایید شد.';
    } elseif ($action === 'return') {
        if ($note === '') {
            $error = 'برای بازگشت جهت اصلاح، درج توضیح الزامی است.';
        } else {
            $stmt = $pdo->prepare("UPDATE dependents SET status = 'needs_correction', admin_note = ?, reviewed_at = NOW(), reviewed_by = ? WHERE id = ?");
            $stmt->execute([$note, $admin['id'], $dependent_id]);
            log_activity($pdo, 'return_dependent', $note, null);
            $success = 'فرد تبعی برای اصلاح به کارمند بازگشت داده شد.';
        }
    } elseif ($action === 'delete') {
        if (!delete_dependent($pdo, $dependent_id)) {
            $error = 'این فرد تبعی حداقل یک درخواست ثبت‌شده دارد و قابل حذف نیست.';
        } else {
            log_activity($pdo, 'delete_dependent', 'حذف توسط مدیر');
            $success = 'فرد تبعی حذف شد.';
        }
    }
}

$relationLabels = ['spouse' => 'همسر', 'father' => 'پدر', 'mother' => 'مادر', 'child' => 'فرزند'];
$genderLabels = ['male' => 'مرد', 'female' => 'زن'];
$allDocLabels = array_merge(required_document_types(), optional_document_types());

$dependents = $pdo->query("
    SELECT d.*, u.full_name AS employee_name
    FROM dependents d
    JOIN users u ON u.id = d.user_id
    ORDER BY (d.status = 'pending') DESC, d.created_at DESC
")->fetchAll();

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

$page_title = 'بررسی افراد تبعی';
include __DIR__ . '/../includes/header.php';
?>

<h4 class="mb-4">بررسی و تایید افراد تبعی</h4>

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

<?php foreach ($dependents as $d): ?>
  <?php $doc_stmt->execute([$d['id']]); $docs = $doc_stmt->fetchAll(); ?>
  <div class="card p-3 mb-3">
    <div class="row">
      <div class="col-md-7">
        <div class="d-flex justify-content-between">
          <strong><?= htmlspecialchars($d['full_name']) ?> (<?= $relationLabels[$d['relation']] ?? '' ?> — کارمند: <?= htmlspecialchars($d['employee_name']) ?>)</strong>
          <span class="badge <?= dependent_status_badge_class($d['status']) ?>"><?= dependent_status_label($d['status']) ?></span>
        </div>
        <table class="table table-sm table-borderless mb-0 mt-2">
          <tr><th class="w-25">جنسیت</th><td><?= $genderLabels[$d['gender']] ?? '-' ?></td></tr>
          <tr><th>کد ملی</th><td><?= htmlspecialchars($d['national_code'] ?? '-') ?></td></tr>
          <tr><th>شماره شناسنامه</th><td><?= htmlspecialchars($d['id_number'] ?? '-') ?></td></tr>
          <tr><th>تاریخ تولد</th><td><?= $d['birth_date'] ? to_jalali_string($d['birth_date']) : '-' ?></td></tr>
          <tr><th>موبایل</th><td><?= htmlspecialchars($d['mobile'] ?? '-') ?></td></tr>
          <tr><th>ایمیل</th><td><?= htmlspecialchars($d['email'] ?? '-') ?></td></tr>
          <tr><th>آدرس</th><td><?= htmlspecialchars($d['address'] ?? '-') ?></td></tr>
          <tr><th>سابقه بیماری خاص</th><td>
            <?php if ($d['has_medical_condition'] === null): ?> - <?php elseif ((int)$d['has_medical_condition'] === 1): ?>
              بله: <?= htmlspecialchars($d['medical_history'] ?? '') ?>
            <?php else: ?> خیر <?php endif; ?>
          </td></tr>
        </table>
        <div class="mt-2 row g-2">
          <?php foreach ($docs as $doc): ?>
            <?php $docUrl = base_url('download_dependent_doc.php?id=' . $doc['id']); ?>
            <div class="col-6 col-md-4">
              <a href="<?= $docUrl ?>" target="_blank" class="text-decoration-none text-body">
                <div class="small fw-medium"><?= htmlspecialchars($allDocLabels[$doc['doc_type']] ?? $doc['doc_type']) ?></div>
                <?php if (is_image_ext($doc['original_name'])): ?>
                  <img src="<?= $docUrl ?>" class="doc-thumb" alt="">
                <?php else: ?>
                  <div class="doc-thumb d-flex align-items-center justify-content-center bg-light text-muted small">📄 PDF</div>
                <?php endif; ?>
              </a>
            </div>
          <?php endforeach; ?>
        </div>
        <?php if ($d['admin_note']): ?>
          <div class="alert alert-warning small mt-2 mb-0">آخرین یادداشت: <?= htmlspecialchars($d['admin_note']) ?></div>
        <?php endif; ?>
      </div>
      <div class="col-md-5">
        <?php if ($d['status'] !== 'approved'): ?>
        <form method="post">
          <?= csrf_field() ?>
          <input type="hidden" name="dependent_id" value="<?= $d['id'] ?>">
          <textarea name="admin_note" class="form-control form-control-sm mb-2" rows="2" placeholder="یادداشت (برای بازگشت جهت اصلاح الزامی است)"></textarea>
          <div class="d-flex gap-2">
            <button type="submit" name="action" value="approve" class="btn btn-success btn-sm flex-fill">تایید</button>
            <button type="submit" name="action" value="return" class="btn btn-danger btn-sm flex-fill">بازگشت برای اصلاح</button>
          </div>
        </form>
        <?php else: ?>
          <p class="text-muted small mb-0">تایید شده در <?= to_jalali_string($d['reviewed_at']) ?></p>
        <?php endif; ?>
        <form method="post" class="mt-2">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="dependent_id" value="<?= $d['id'] ?>">
          <button type="submit" class="btn btn-sm btn-outline-danger w-100" onclick="return confirm('این فرد تبعی برای همیشه حذف شود؟ این عملیات قابل بازگشت نیست.')">حذف فرد تبعی</button>
        </form>
      </div>
    </div>
  </div>
<?php endforeach; ?>
<?php if (!$dependents): ?><p class="text-muted">فرد تبعی ثبت نشده است.</p><?php endif; ?>

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