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

$user = current_user();
$dependents_enabled = get_setting($pdo, 'dependents_enabled', '1') === '1';

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_dependent') {
    verify_csrf();
    $dep_id = (int)$_POST['dependent_id'];
    $stmt = $pdo->prepare("SELECT id, full_name FROM dependents WHERE id = ? AND user_id = ?");
    $stmt->execute([$dep_id, $user['id']]);
    $depToDelete = $stmt->fetch();

    if (!$depToDelete) {
        $error = 'فرد تبعی یافت نشد.';
    } elseif (!delete_dependent($pdo, $dep_id)) {
        $error = 'این فرد تبعی حداقل یک درخواست ثبت‌شده دارد و قابل حذف نیست.';
    } else {
        log_activity($pdo, 'delete_dependent', $depToDelete['full_name']);
        $success = 'فرد تبعی حذف شد.';
    }
}

$stmt = $pdo->prepare("SELECT * FROM dependents WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user['id']]);
$dependents = $stmt->fetchAll();

$doc_stmt = $pdo->prepare("SELECT * FROM dependent_documents WHERE dependent_id = ?");
$docLabels = required_document_types();
$optionalLabels = optional_document_types();
$allDocLabels = array_merge($docLabels, $optionalLabels);

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

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <h4 class="mb-0">مدیریت افراد تبعی</h4>
  <?php if ($dependents_enabled): ?>
    <a href="add_dependent.php" class="btn btn-primary btn-sm">+ افزودن فرد تبعی جدید</a>
  <?php endif; ?>
</div>

<?php if (!$dependents_enabled): ?>
  <div class="alert alert-warning">امکان ثبت افراد تبعی در حال حاضر توسط مدیر غیرفعال است.</div>
<?php endif; ?>

<?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; ?>

<div class="card p-3">
  <?php if (!$dependents): ?>
    <div class="empty-state">
      <img src="<?= base_url('assets/img/empty-state.svg') ?>" alt="">
      <div>هنوز فردی ثبت نکرده‌اید.</div>
    </div>
  <?php else: ?>
    <div class="table-responsive">
    <table class="table table-bordered align-middle mb-0">
      <thead class="table-light"><tr><th>نام</th><th>نسبت</th><th>جنسیت</th><th>تاریخ تولد</th><th>وضعیت</th><th>مدارک</th><th></th></tr></thead>
      <tbody>
        <?php foreach ($dependents as $d): ?>
          <?php $doc_stmt->execute([$d['id']]); $docs = $doc_stmt->fetchAll(); ?>
          <tr>
            <td><?= htmlspecialchars($d['full_name']) ?></td>
            <td><?= $relationLabels[$d['relation']] ?? $d['relation'] ?></td>
            <td><?= $genderLabels[$d['gender']] ?? '-' ?></td>
            <td><?= $d['birth_date'] ? to_jalali_string($d['birth_date']) : '-' ?></td>
            <td>
              <span class="badge <?= dependent_status_badge_class($d['status']) ?>"><?= dependent_status_label($d['status']) ?></span>
              <?php if ($d['status'] === 'needs_correction' && $d['admin_note']): ?>
                <div class="small text-danger mt-1"><?= htmlspecialchars($d['admin_note']) ?></div>
              <?php endif; ?>
            </td>
            <td>
              <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#docsModal<?= $d['id'] ?>">
                <?= icon('paperclip') ?> مشاهده مدارک (<?= fa_num(count($docs)) ?>)
              </button>
            </td>
            <td class="text-nowrap">
              <a href="edit_dependent.php?id=<?= $d['id'] ?>" class="btn btn-sm btn-outline-secondary">ویرایش</a>
              <form method="post" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="delete_dependent">
                <input type="hidden" name="dependent_id" value="<?= $d['id'] ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('این فرد تبعی برای همیشه حذف شود؟ این عملیات قابل بازگشت نیست.')">حذف</button>
              </form>
            </td>
          </tr>

          <div class="modal fade" id="docsModal<?= $d['id'] ?>" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
              <div class="modal-content">
                <div class="modal-header">
                  <h6 class="modal-title">مدارک <?= htmlspecialchars($d['full_name']) ?></h6>
                  <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                  <?php if (!$docs): ?>
                    <p class="text-muted mb-0">مدرکی آپلود نشده است.</p>
                  <?php else: ?>
                    <div class="row g-3">
                      <?php foreach ($docs as $doc): ?>
                        <?php $docUrl = base_url('download_dependent_doc.php?id=' . $doc['id']); ?>
                        <div class="col-6">
                          <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 endif; ?>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </tbody>
    </table>
    </div>
  <?php endif; ?>
</div>

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