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

$user = current_user();
$dependent_id = (int)($_GET['id'] ?? $_POST['dependent_id'] ?? 0);

$stmt = $pdo->prepare("SELECT * FROM dependents WHERE id = ? AND user_id = ?");
$stmt->execute([$dependent_id, $user['id']]);
$dep = $stmt->fetch();

if (!$dep) {
    $_SESSION['flash_error'] = 'فرد تبعی یافت نشد.';
    header('Location: ' . base_url('employee/dependents.php'));
    exit;
}

$locked = ($dep['status'] === 'approved');
$lockedFields = dependent_locked_fields();
$relationLabels = ['spouse' => 'همسر', 'father' => 'پدر', 'mother' => 'مادر', 'child' => 'فرزند'];
$docLabels = required_document_types();
$optionalLabels = optional_document_types();
$allDocLabels = array_merge($docLabels, $optionalLabels);

$doc_stmt = $pdo->prepare("SELECT * FROM dependent_documents WHERE dependent_id = ?");
$doc_stmt->execute([$dependent_id]);
$existingDocs = $doc_stmt->fetchAll();
$uploadedTypes = array_column($existingDocs, 'doc_type');

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();

    $full_name = in_array('full_name', $lockedFields) && $locked ? $dep['full_name'] : trim($_POST['full_name'] ?? '');
    $relation = in_array('relation', $lockedFields) && $locked ? $dep['relation'] : ($_POST['relation'] ?? '');
    $national_code = in_array('national_code', $lockedFields) && $locked ? $dep['national_code'] : trim($_POST['national_code'] ?? '');
    $id_number = in_array('id_number', $lockedFields) && $locked ? $dep['id_number'] : trim($_POST['id_number'] ?? '');
    $gender = in_array('gender', $lockedFields) && $locked ? $dep['gender'] : ($_POST['gender'] ?? '');

    $mobile = trim($_POST['mobile'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $has_medical = $_POST['has_medical_condition'] ?? '';
    $medical_history = trim($_POST['medical_history'] ?? '');

    if ($locked && in_array('birth_date', $lockedFields)) {
        $birth_date_sql = $dep['birth_date'];
    } else {
        $birth_date_j = trim($_POST['birth_date'] ?? '');
        $birth_g = parse_jalali_date($birth_date_j);
        if (!$birth_g || !is_jalali_date_not_future($birth_date_j)) {
            $error = 'تاریخ تولد نامعتبر است یا در آینده است.';
        } else {
            $birth_date_sql = sprintf('%04d-%02d-%02d', $birth_g[0], $birth_g[1], $birth_g[2]);
        }
    }

    if (!$error && ($mobile === '' || $email === '' || $address === '')) {
        $error = 'موبایل، ایمیل و آدرس الزامی هستند.';
    }
    if (!$error && !in_array($has_medical, ['0', '1'])) {
        $error = 'به سوال «آیا بیماری خاصی دارد؟» پاسخ دهید.';
    }
    if (!$error && $has_medical === '1' && $medical_history === '') {
        $error = 'توضیح سوابق بیماری الزامی است.';
    }

    if (!$error) {
        $newStatus = ($dep['status'] === 'needs_correction') ? 'pending' : $dep['status'];

        $stmt2 = $pdo->prepare("
            UPDATE dependents
            SET full_name = ?, relation = ?, national_code = ?, id_number = ?, gender = ?,
                mobile = ?, phone = ?, email = ?, address = ?, birth_date = ?, has_medical_condition = ?, medical_history = ?, status = ?
            WHERE id = ?
        ");
        $stmt2->execute([
            $full_name, $relation, $national_code, $id_number, $gender,
            $mobile, $phone ?: null, $email, $address, $birth_date_sql, (int)$has_medical, ($has_medical === '1') ? $medical_history : null, $newStatus,
            $dependent_id,
        ]);

        $docStmt = $pdo->prepare("INSERT INTO dependent_documents (dependent_id, doc_type, file_path, original_name) VALUES (?, ?, ?, ?)");
        foreach ($allDocLabels 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']]);
                }
            }
        }

        log_activity($pdo, 'edit_dependent', 'ویرایش اطلاعات فرد تبعی: ' . $full_name);
        $_SESSION['flash_success'] = 'اطلاعات با موفقیت ذخیره شد.' . ($newStatus === 'pending' ? ' برای بررسی مجدد به مدیر ارسال شد.' : '');
        header('Location: ' . base_url('employee/dependents.php'));
        exit;
    }
}

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

<h4 class="mb-4">ویرایش اطلاعات: <?= htmlspecialchars($dep['full_name']) ?></h4>

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

<?php if ($dep['status'] === 'needs_correction' && $dep['admin_note']): ?>
  <div class="alert alert-danger">مدیر این مورد را برای اصلاح بازگردانده: <?= htmlspecialchars($dep['admin_note']) ?></div>
<?php elseif ($locked): ?>
  <div class="alert alert-info small">این فرد تبعی قبلاً تایید شده؛ فیلدهای هویتی (نام، نسبت، کد ملی، شماره شناسنامه، جنسیت، تاریخ تولد) دیگر قابل ویرایش نیستند. فقط اطلاعات تماس/آدرس/سوابق و مدارک قابل بروزرسانی هستند.</div>
<?php endif; ?>

<div class="card p-4">
  <form method="post" enctype="multipart/form-data" novalidate>
    <?= csrf_field() ?>
    <input type="hidden" name="dependent_id" value="<?= $dep['id'] ?>">
    <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 value="<?= htmlspecialchars($dep['full_name']) ?>" <?= $locked ? 'disabled' : '' ?>>
      </div>
      <div class="col-md-4">
        <label class="form-label">نسبت *</label>
        <select name="relation" class="form-select" required <?= $locked ? 'disabled' : '' ?>>
          <?php foreach ($relationLabels as $val => $label): ?>
            <option value="<?= $val ?>" <?= $dep['relation'] === $val ? 'selected' : '' ?>><?= $label ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">جنسیت *</label>
        <select name="gender" class="form-select" required <?= $locked ? 'disabled' : '' ?>>
          <option value="male" <?= $dep['gender'] === 'male' ? 'selected' : '' ?>>مرد</option>
          <option value="female" <?= $dep['gender'] === 'female' ? 'selected' : '' ?>>زن</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">تاریخ تولد *</label>
        <input type="text" name="birth_date" class="form-control <?= $locked ? '' : 'jalali-date-input' ?>" autocomplete="off"
               value="<?= $dep['birth_date'] ? to_jalali_string_latin($dep['birth_date']) : '' ?>" <?= $locked ? 'disabled' : 'required' ?>>
      </div>
      <div class="col-md-3">
        <label class="form-label">کد ملی *</label>
        <input type="text" name="national_code" class="form-control" inputmode="numeric" required value="<?= htmlspecialchars($dep['national_code']) ?>" <?= $locked ? 'disabled' : '' ?>>
      </div>
      <div class="col-md-3">
        <label class="form-label">شماره شناسنامه *</label>
        <input type="text" name="id_number" class="form-control" inputmode="numeric" required value="<?= htmlspecialchars($dep['id_number']) ?>" <?= $locked ? 'disabled' : '' ?>>
      </div>
      <div class="col-md-4">
        <label class="form-label">شماره همراه *</label>
        <input type="text" name="mobile" class="form-control" inputmode="numeric" required value="<?= htmlspecialchars($dep['mobile'] ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">ایمیل *</label>
        <input type="email" name="email" class="form-control" required value="<?= htmlspecialchars($dep['email'] ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">شماره ثابت (اختیاری)</label>
        <input type="text" name="phone" class="form-control" inputmode="numeric" value="<?= htmlspecialchars($dep['phone'] ?? '') ?>">
      </div>
      <div class="col-12">
        <label class="form-label">آدرس *</label>
        <textarea name="address" class="form-control" rows="2" required><?= htmlspecialchars($dep['address'] ?? '') ?></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="editDepMedYes" required <?= (isset($dep['has_medical_condition']) && (int)$dep['has_medical_condition'] === 1) ? 'checked' : '' ?>>
          <label class="form-check-label" for="editDepMedYes">بله</label>
        </div>
        <div class="form-check form-check-inline">
          <input type="radio" name="has_medical_condition" value="0" class="form-check-input" id="editDepMedNo" required <?= (isset($dep['has_medical_condition']) && (int)$dep['has_medical_condition'] === 0) ? 'checked' : '' ?>>
          <label class="form-check-label" for="editDepMedNo">خیر</label>
        </div>
      </div>
      <div class="col-12" id="editDepMedicalHistoryWrap" style="display:none;">
        <label class="form-label">توضیح سوابق بیماری *</label>
        <textarea name="medical_history" class="form-control" rows="2"><?= htmlspecialchars($dep['medical_history'] ?? '') ?></textarea>
      </div>
    </div>

    <hr class="my-4">
    <h6>مدارک هویتی</h6>
    <div class="row g-3">
      <?php foreach ($docLabels as $type => $label): ?>
        <div class="col-md-4">
          <label class="form-label small">
            <?= htmlspecialchars($label) ?> <?= in_array($type, $uploadedTypes) ? '' : '*' ?>
            <?php if (in_array($type, $uploadedTypes)): ?><span class="badge bg-success">آپلود شده</span><?php endif; ?>
          </label>
          <input type="file" name="doc[<?= $type ?>]" class="form-control form-control-sm" <?= in_array($type, $uploadedTypes) ? '' : 'required' ?> accept=".jpg,.jpeg,.png,.pdf">
        </div>
      <?php endforeach; ?>
      <div class="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>
    </div>

    <?php if ($locked): ?>
      <input type="hidden" name="full_name" value="<?= htmlspecialchars($dep['full_name']) ?>">
      <input type="hidden" name="relation" value="<?= htmlspecialchars($dep['relation']) ?>">
      <input type="hidden" name="gender" value="<?= htmlspecialchars($dep['gender']) ?>">
      <input type="hidden" name="national_code" value="<?= htmlspecialchars($dep['national_code']) ?>">
      <input type="hidden" name="id_number" value="<?= htmlspecialchars($dep['id_number']) ?>">
      <input type="hidden" name="birth_date" value="<?= $dep['birth_date'] ? to_jalali_string_latin($dep['birth_date']) : '' ?>">
    <?php endif; ?>
    <button type="submit" class="btn btn-primary mt-3">ذخیره تغییرات</button>
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var yes = document.getElementById('editDepMedYes');
    var no = document.getElementById('editDepMedNo');
    var wrap = document.getElementById('editDepMedicalHistoryWrap');
    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'; ?>
