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

$user = current_user();

if (get_setting($pdo, 'dependents_enabled', '1') !== '1') {
    $_SESSION['flash_error'] = 'امکان ثبت افراد تبعی در حال حاضر توسط مدیر غیرفعال است.';
    header('Location: ' . base_url('employee/dashboard.php'));
    exit;
}

$dependent_share_percent = (float)get_setting($pdo, 'dependent_share_percent', 50);
$consent_text = dependent_consent_text($dependent_share_percent);
$docLabels = required_document_types();
$optionalLabels = optional_document_types();

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $full_name = trim($_POST['full_name'] ?? '');
    $relation = $_POST['relation'] ?? '';
    $national_code = trim($_POST['national_code'] ?? '');
    $gender = $_POST['gender'] ?? '';
    $id_number = trim($_POST['id_number'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $birth_date_j = trim($_POST['birth_date'] ?? '');
    $has_medical = $_POST['has_medical_condition'] ?? '';
    $medical_history = trim($_POST['medical_history'] ?? '');
    $consent = isset($_POST['consent']);

    $validRelations = ['spouse', 'father', 'mother', 'child'];
    $birth_g = parse_jalali_date($birth_date_j);

    if ($full_name === '' || !in_array($relation, $validRelations)) {
        $error = 'نام و نسبت را به‌درستی وارد کنید.';
    } elseif (!in_array($gender, ['male', 'female'])) {
        $error = 'جنسیت را انتخاب کنید.';
    } elseif ($national_code === '' || $id_number === '' || $mobile === '' || $email === '' || $address === '') {
        $error = 'همه فیلدهای الزامی را تکمیل کنید.';
    } elseif (!$birth_g) {
        $error = 'تاریخ تولد را به فرمت درست (مثلاً 1370/05/10) وارد کنید.';
    } elseif (!is_jalali_date_not_future($birth_date_j)) {
        $error = 'تاریخ تولد نمی‌تواند در آینده باشد.';
    } elseif (!in_array($has_medical, ['0', '1'])) {
        $error = 'به سوال «آیا بیماری خاصی دارد؟» پاسخ دهید.';
    } elseif ($has_medical === '1' && $medical_history === '') {
        $error = 'توضیح سوابق بیماری الزامی است.';
    } elseif (!$consent) {
        $error = 'برای ثبت فرد تبعی باید متن رضایت‌نامه را تایید کنید.';
    } else {
        $missingDocs = [];
        foreach ($docLabels as $type => $label) {
            if (empty($_FILES['doc']['name'][$type] ?? '')) $missingDocs[] = $label;
        }
        if ($missingDocs) {
            $error = 'مدارک زیر الزامی هستند: ' . implode('، ', $missingDocs);
        }
    }

    if (!$error) {
        try {
            $pdo->beginTransaction();
            [$gy, $gm, $gd] = $birth_g;
            $birth_date_sql = sprintf('%04d-%02d-%02d', $gy, $gm, $gd);

            $stmt = $pdo->prepare("
                INSERT INTO dependents (user_id, full_name, relation, national_code, gender, id_number, mobile, phone, email, address, birth_date, has_medical_condition, medical_history)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $user['id'], $full_name, $relation, $national_code, $gender, $id_number, $mobile, $phone ?: null, $email,
                $address, $birth_date_sql, (int)$has_medical, ($has_medical === '1') ? $medical_history : null,
            ]);
            $dependent_id = $pdo->lastInsertId();

            $docStmt = $pdo->prepare("INSERT INTO dependent_documents (dependent_id, doc_type, file_path, original_name) VALUES (?, ?, ?, ?)");
            foreach (array_merge($docLabels, $optionalLabels) as $type => $label) {
                if (empty($_FILES['doc']['name'][$type] ?? '')) continue;
                $single = [
                    'name' => $_FILES['doc']['name'][$type],
                    'type' => $_FILES['doc']['type'][$type],
                    'tmp_name' => $_FILES['doc']['tmp_name'][$type],
                    'error' => $_FILES['doc']['error'][$type],
                    'size' => $_FILES['doc']['size'][$type],
                ];
                $up = handle_document_upload($single, 'dependent_' . $dependent_id);
                if ($up) {
                    $docStmt->execute([$dependent_id, $type, $up['file_path'], $up['original_name']]);
                }
            }
            if (!empty($_FILES['doc_other']['name']) && is_array($_FILES['doc_other']['name'])) {
                $count = count($_FILES['doc_other']['name']);
                for ($i = 0; $i < $count; $i++) {
                    if ($_FILES['doc_other']['error'][$i] === UPLOAD_ERR_NO_FILE) continue;
                    $single = [
                        'name' => $_FILES['doc_other']['name'][$i],
                        'type' => $_FILES['doc_other']['type'][$i],
                        'tmp_name' => $_FILES['doc_other']['tmp_name'][$i],
                        'error' => $_FILES['doc_other']['error'][$i],
                        'size' => $_FILES['doc_other']['size'][$i],
                    ];
                    $up = handle_document_upload($single, 'dependent_' . $dependent_id);
                    if ($up) {
                        $docStmt->execute([$dependent_id, 'other', $up['file_path'], $up['original_name']]);
                    }
                }
            }

            $pdo->commit();
            log_activity($pdo, 'add_dependent', $full_name . ' (' . $relation . ')');
            $_SESSION['flash_success'] = 'فرد تبعی با موفقیت ثبت شد.';
            header('Location: ' . base_url('employee/dependents.php'));
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = 'خطا: ' . $e->getMessage();
        }
    }
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <h4 class="mb-0">افزودن فرد تبعی جدید</h4>
  <a href="dependents.php" class="btn btn-outline-secondary btn-sm">بازگشت به لیست</a>
</div>

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

<div class="card p-4">
  <div class="border rounded p-3 mb-3 small" style="white-space: pre-wrap; background:#fafafa;"><?= htmlspecialchars($consent_text) ?></div>
  <form method="post" enctype="multipart/form-data" novalidate>
    <?= csrf_field() ?>
    <div class="row g-3">
      <div class="col-md-8">
        <label class="form-label">نام و نام خانوادگی *</label>
        <input type="text" name="full_name" class="form-control" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">نسبت *</label>
        <select name="relation" class="form-select" required>
          <option value="">— انتخاب کنید —</option>
          <option value="spouse">همسر</option>
          <option value="father">پدر</option>
          <option value="mother">مادر</option>
          <option value="child">فرزند</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">جنسیت *</label>
        <select name="gender" class="form-select" required>
          <option value="">— انتخاب کنید —</option>
          <option value="male">مرد</option>
          <option value="female">زن</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">تاریخ تولد *</label>
        <input type="text" name="birth_date" class="form-control jalali-date-input" required autocomplete="off" placeholder="1370/05/10">
      </div>
      <div class="col-md-3">
        <label class="form-label">کد ملی *</label>
        <input type="text" name="national_code" class="form-control" inputmode="numeric" required>
      </div>
      <div class="col-md-3">
        <label class="form-label">شماره شناسنامه *</label>
        <input type="text" name="id_number" class="form-control" inputmode="numeric" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">شماره همراه *</label>
        <input type="text" name="mobile" class="form-control" inputmode="numeric" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">ایمیل *</label>
        <input type="email" name="email" class="form-control" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">شماره ثابت (اختیاری)</label>
        <input type="text" name="phone" class="form-control" inputmode="numeric">
      </div>
      <div class="col-12">
        <label class="form-label">آدرس *</label>
        <textarea name="address" class="form-control" rows="2" required></textarea>
      </div>

      <div class="col-12">
        <label class="form-label d-block">آیا بیماری خاصی دارد؟ *</label>
        <div class="form-check form-check-inline">
          <input type="radio" name="has_medical_condition" value="1" class="form-check-input" id="depMedYes" required>
          <label class="form-check-label" for="depMedYes">بله</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="radio" name="has_medical_condition" value="0" class="form-check-input" id="depMedNo" required>
          <label class="form-check-label" for="depMedNo">خیر</label>
        </div>
      </div>
      <div class="col-12" id="depMedicalHistoryWrap" style="display:none;">
        <label class="form-label">توضیح سوابق بیماری *</label>
        <textarea name="medical_history" class="form-control" rows="2"></textarea>
      </div>
    </div>

    <hr class="my-4">
    <h6>مدارک هویتی</h6>
    <div class="row g-3">
      <?php foreach ($docLabels as $type => $label): ?>
        <div class="col-6 col-md-4">
          <label class="form-label small"><?= htmlspecialchars($label) ?> *</label>
          <input type="file" name="doc[<?= $type ?>]" class="form-control form-control-sm" required accept=".jpg,.jpeg,.png,.pdf">
        </div>
      <?php endforeach; ?>
      <div class="col-6 col-md-4">
        <label class="form-label small">سایر مدارک (اختیاری)</label>
        <input type="file" name="doc_other[]" class="form-control form-control-sm" multiple accept=".jpg,.jpeg,.png,.pdf">
        <div class="form-text">اگر شناسنامه جدید است و صفحات سوم/چهارم ندارد، توضیح آن را همراه مدرک مرتبط از همین قسمت بارگذاری کنید.</div>
      </div>
    </div>

    <div class="form-check mt-3 mb-3">
      <input type="checkbox" name="consent" value="1" class="form-check-input" id="consentCheck" required>
      <label class="form-check-label" for="consentCheck">متن رضایت‌نامه فوق را مطالعه کردم و می‌پذیرم.</label>
    </div>
    <button type="submit" class="btn btn-primary">ثبت فرد تبعی</button>
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var yes = document.getElementById('depMedYes');
    var no = document.getElementById('depMedNo');
    var wrap = document.getElementById('depMedicalHistoryWrap');
    var textarea = wrap.querySelector('textarea');
    function update() {
        if (yes.checked) {
            wrap.style.display = '';
            textarea.setAttribute('required', 'required');
        } else {
            wrap.style.display = 'none';
            textarea.removeAttribute('required');
            textarea.classList.remove('is-invalid');
        }
    }
    yes.addEventListener('change', update);
    no.addEventListener('change', update);
    update();
});
</script>

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