<?php $__template->layout('Layout.main'); ?>
<?php $isEdit = $profile !== null; ?>
<?php $__template->section('title'); ?><?= $isEdit ? 'تعديل بيانات الموظف' : 'إضافة موظف جديد' ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/hr/employees" class="btn btn-secondary">رجوع</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>
<form method="POST" action="<?= $isEdit ? '/hr/employees/' . (int) $profile->id : '/hr/employees' ?>">
    <?= csrf_field() ?>

    <?php if (!$isEdit): ?>
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:16px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;font-size:16px;">ربط بحساب النظام</h3></div>
        <div style="padding:16px;">
            <label style="display:block;margin-bottom:4px;font-size:13px;">حساب الموظف في النظام <span style="color:#DC2626;">*</span></label>
            <select name="employee_id" class="form-control" required>
                <option value="">-- اختر --</option>
                <?php foreach ($unlinked as $u): ?>
                <option value="<?= (int) $u['id'] ?>" <?= old('employee_id') == $u['id'] ? 'selected' : '' ?>><?= e($u['full_name_ar'] . ' (' . $u['username'] . ')') ?></option>
                <?php endforeach; ?>
            </select>
            <?php if (empty($unlinked)): ?>
            <p style="margin-top:8px;color:#DC2626;font-size:13px;">لا يوجد حسابات موظفين بدون ملفات HR. أضف موظف في إدارة المستخدمين أولاً.</p>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:16px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;font-size:16px;">البيانات الشخصية</h3></div>
        <div style="padding:16px;display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الاسم الأول بالعربي <span style="color:#DC2626;">*</span></label>
                <input type="text" name="first_name_ar" value="<?= e(old('first_name_ar') ?? ($isEdit ? $profile->first_name_ar : '')) ?>" class="form-control" required>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">اسم العائلة بالعربي <span style="color:#DC2626;">*</span></label>
                <input type="text" name="last_name_ar" value="<?= e(old('last_name_ar') ?? ($isEdit ? $profile->last_name_ar : '')) ?>" class="form-control" required>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الاسم الأول بالإنجليزي</label>
                <input type="text" name="first_name_en" value="<?= e(old('first_name_en') ?? ($isEdit ? $profile->first_name_en : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">اسم العائلة بالإنجليزي</label>
                <input type="text" name="last_name_en" value="<?= e(old('last_name_en') ?? ($isEdit ? $profile->last_name_en : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الرقم القومي <span style="color:#DC2626;">*</span></label>
                <input type="text" name="national_id" value="<?= e(old('national_id') ?? ($isEdit ? $profile->national_id : '')) ?>" class="form-control" maxlength="14" required id="nidInput" style="direction:ltr;text-align:left;">
                <small id="nidStatus" style="display:none;margin-top:4px;font-size:11px;"></small>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">تاريخ الميلاد</label>
                <input type="date" name="date_of_birth" value="<?= e(old('date_of_birth') ?? ($isEdit ? $profile->date_of_birth : '')) ?>" class="form-control" id="dobInput" readonly style="background:#F9FAFB;">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الجنس</label>
                <select class="form-control" id="genderDisplay" disabled style="background:#F9FAFB;">
                    <?php foreach ($genders as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('gender') ?? ($isEdit ? $profile->gender : 'male')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="hidden" name="gender" id="genderHidden" value="<?= e(old('gender') ?? ($isEdit ? $profile->gender : 'male')) ?>">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الحالة الاجتماعية</label>
                <select name="marital_status" class="form-control">
                    <?php foreach ($maritalStatuses as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('marital_status') ?? ($isEdit ? $profile->marital_status : 'single')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الديانة</label>
                <select name="religion" class="form-control">
                    <?php foreach ($religions as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('religion') ?? ($isEdit ? $profile->religion : 'muslim')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الجنسية</label>
                <input type="text" name="nationality" value="<?= e(old('nationality') ?? ($isEdit ? $profile->nationality : 'egyptian')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الهاتف</label>
                <input type="text" name="phone" value="<?= e(old('phone') ?? ($isEdit ? $profile->phone : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">البريد الإلكتروني</label>
                <input type="email" name="email" value="<?= e(old('email') ?? ($isEdit ? $profile->email : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">موقف التجنيد</label>
                <select name="military_status" class="form-control">
                    <option value="">-- غير محدد --</option>
                    <?php foreach ($militaryStatuses as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('military_status') ?? ($isEdit ? $profile->military_status : '')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="grid-column:1/-1;">
                <label style="display:block;margin-bottom:4px;font-size:13px;">العنوان</label>
                <input type="text" name="address" value="<?= e(old('address') ?? ($isEdit ? $profile->address : '')) ?>" class="form-control">
            </div>
        </div>
    </div>

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:16px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;font-size:16px;">المؤهل الدراسي</h3></div>
        <div style="padding:16px;display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">المؤهل</label>
                <input type="text" name="education_qualification" value="<?= e(old('education_qualification') ?? ($isEdit ? $profile->education_qualification : '')) ?>" class="form-control" placeholder="مثال: بكالوريوس - ماجستير - دبلوم">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">التخصص</label>
                <input type="text" name="education_specialization" value="<?= e(old('education_specialization') ?? ($isEdit ? $profile->education_specialization : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">سنة التخرج</label>
                <input type="number" name="education_graduation_year" value="<?= e(old('education_graduation_year') ?? ($isEdit ? $profile->education_graduation_year : '')) ?>" class="form-control" min="1970" max="2030" placeholder="مثال: 2015">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">التقدير</label>
                <input type="text" name="education_grade" value="<?= e(old('education_grade') ?? ($isEdit ? $profile->education_grade : '')) ?>" class="form-control" placeholder="مثال: جيد جداً - امتياز">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الجامعة / المعهد</label>
                <input type="text" name="education_university" value="<?= e(old('education_university') ?? ($isEdit ? $profile->education_university : '')) ?>" class="form-control">
            </div>
        </div>
    </div>

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:16px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;font-size:16px;">البيانات الوظيفية</h3></div>
        <div style="padding:16px;display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">كود البصمة</label>
                <input type="text" name="fingerprint_code" value="<?= e(old('fingerprint_code') ?? ($isEdit ? $profile->fingerprint_code : '')) ?>" class="form-control" placeholder="رقم الموظف في جهاز البصمة">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الإدارة</label>
                <select id="idara_select" class="form-control" onchange="loadAqsam()">
                    <option value="">-- اختر الإدارة --</option>
                    <?php foreach ($idaras as $ida): ?>
                    <option value="<?= (int) $ida['id'] ?>" <?= (old('idara_id') ?? ($isEdit ? ($profile->idara_id ?? '') : '')) == $ida['id'] ? 'selected' : '' ?>><?= e($ida['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">القسم</label>
                <select name="department_id" id="qism_select" class="form-control">
                    <option value="">-- اختر القسم --</option>
                    <?php foreach ($departments as $d): ?>
                    <?php if (($d['department_type'] ?? '') === 'qism'): ?>
                    <option value="<?= (int) $d['id'] ?>" data-idara="<?= (int) ($d['parent_id'] ?? 0) ?>" <?= (old('department_id') ?? ($isEdit ? $profile->department_id : '')) == $d['id'] ? 'selected' : '' ?>><?= e($d['name_ar']) ?></option>
                    <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">المسمى الوظيفي</label>
                <select name="job_title_id" class="form-control">
                    <option value="">-- اختر --</option>
                    <?php foreach ($jobTitles as $jt): ?>
                    <option value="<?= (int) $jt['id'] ?>" <?= (old('job_title_id') ?? ($isEdit ? $profile->job_title_id : '')) == $jt['id'] ? 'selected' : '' ?>><?= e($jt['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">المدير المباشر</label>
                <select name="direct_manager_id" class="form-control">
                    <option value="">-- بدون --</option>
                    <?php foreach ($managers as $m): ?>
                    <option value="<?= (int) $m['id'] ?>" <?= (old('direct_manager_id') ?? ($isEdit ? $profile->direct_manager_id : '')) == $m['id'] ? 'selected' : '' ?>><?= e($m['first_name_ar'] . ' ' . $m['last_name_ar'] . ' (' . $m['employee_number'] . ')') ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">تاريخ التعيين <span style="color:#DC2626;">*</span></label>
                <input type="date" name="hire_date" value="<?= e(old('hire_date') ?? ($isEdit ? $profile->hire_date : '')) ?>" class="form-control" required>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">نوع التوظيف</label>
                <select name="employment_type" class="form-control">
                    <?php foreach ($types as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('employment_type') ?? ($isEdit ? $profile->employment_type : 'full_time')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">نوع العمالة</label>
                <select name="workforce_type" class="form-control">
                    <?php foreach ($workforceTypes as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('workforce_type') ?? ($isEdit ? $profile->workforce_type : 'insured')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">نهاية فترة الاختبار</label>
                <input type="date" name="probation_end_date" value="<?= e(old('probation_end_date') ?? ($isEdit ? $profile->probation_end_date : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الحالة الوظيفية</label>
                <select name="employment_status" class="form-control">
                    <?php foreach ($statuses as $k => $v): ?>
                    <option value="<?= e($k) ?>" <?= (old('employment_status') ?? ($isEdit ? $profile->employment_status : 'active')) === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </div>

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:16px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;font-size:16px;">البيانات المالية والتأمينية</h3></div>
        <div style="padding:16px;display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الراتب الأساسي <span style="color:#DC2626;">*</span></label>
                <input type="number" name="basic_salary" value="<?= e(old('basic_salary') ?? ($isEdit ? $profile->basic_salary : '0.00')) ?>" class="form-control" step="0.01" min="0" required>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">هيكل الرواتب</label>
                <select name="salary_structure_id" class="form-control">
                    <option value="">-- اختر --</option>
                    <?php foreach ($structures as $s): ?>
                    <option value="<?= (int) $s['id'] ?>" <?= (old('salary_structure_id') ?? ($isEdit ? $profile->salary_structure_id : '')) == $s['id'] ? 'selected' : '' ?>><?= e($s['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الأجر التأميني</label>
                <input type="text" name="insurable_salary" value="<?= e(old('insurable_salary') ?? ($isEdit ? $profile->insurable_salary : '')) ?>" class="form-control" placeholder="إذا يختلف عن الأساسي">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الرقم التأميني</label>
                <input type="text" name="insurance_number" value="<?= e(old('insurance_number') ?? ($isEdit ? $profile->insurance_number : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">تاريخ التأمين</label>
                <input type="date" name="insurance_start_date" value="<?= e(old('insurance_start_date') ?? ($isEdit ? $profile->insurance_start_date : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">رقم البطاقة الضريبية</label>
                <input type="text" name="tax_card_number" value="<?= e(old('tax_card_number') ?? ($isEdit ? $profile->tax_card_number : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">اسم البنك</label>
                <input type="text" name="bank_name" value="<?= e(old('bank_name') ?? ($isEdit ? $profile->bank_name : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">رقم الحساب البنكي</label>
                <input type="text" name="bank_account_number" value="<?= e(old('bank_account_number') ?? ($isEdit ? $profile->bank_account_number : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">IBAN</label>
                <input type="text" name="bank_iban" value="<?= e(old('bank_iban') ?? ($isEdit ? $profile->bank_iban : '')) ?>" class="form-control">
            </div>
        </div>
    </div>

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:16px;border-bottom:1px solid #E5E7EB;"><h3 style="margin:0;font-size:16px;">بيانات إضافية</h3></div>
        <div style="padding:16px;display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">اسم جهة الاتصال الطارئ</label>
                <input type="text" name="emergency_contact_name" value="<?= e(old('emergency_contact_name') ?? ($isEdit ? $profile->emergency_contact_name : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">هاتف جهة الاتصال الطارئ</label>
                <input type="text" name="emergency_contact_phone" value="<?= e(old('emergency_contact_phone') ?? ($isEdit ? $profile->emergency_contact_phone : '')) ?>" class="form-control">
            </div>
            <div style="grid-column:1/-1;">
                <label style="display:block;margin-bottom:4px;font-size:13px;">ملاحظات</label>
                <textarea name="notes" class="form-control" rows="3"><?= e(old('notes') ?? ($isEdit ? $profile->notes : '')) ?></textarea>
            </div>
        </div>
    </div>

    <div style="display:flex;gap:10px;justify-content:flex-end;">
        <a href="/hr/employees" class="btn btn-secondary">إلغاء</a>
        <button type="submit" class="btn btn-primary"><?= $isEdit ? 'تحديث' : 'حفظ' ?></button>
    </div>
</form>

<script>
function loadAqsam() {
    var idaraId = document.getElementById('idara_select').value;
    var qismSelect = document.getElementById('qism_select');
    var options = qismSelect.querySelectorAll('option[data-idara]');
    var currentVal = qismSelect.value;
    options.forEach(function(opt) {
        if (!idaraId) { opt.style.display = ''; return; }
        opt.style.display = opt.getAttribute('data-idara') === idaraId ? '' : 'none';
        if (opt.style.display === 'none' && opt.value === currentVal) qismSelect.value = '';
    });
}
document.addEventListener('DOMContentLoaded', function() {
    var qismSelect = document.getElementById('qism_select');
    var idaraSelect = document.getElementById('idara_select');
    var selectedQism = qismSelect.value;
    if (selectedQism) {
        var opt = qismSelect.querySelector('option[value="' + selectedQism + '"]');
        if (opt && opt.getAttribute('data-idara')) {
            idaraSelect.value = opt.getAttribute('data-idara');
        }
    }
    loadAqsam();
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var nidInput = document.getElementById('nidInput');
    var nidStatus = document.getElementById('nidStatus');
    var dobInput = document.getElementById('dobInput');
    var genderDisplay = document.getElementById('genderDisplay');
    var genderHidden = document.getElementById('genderHidden');

    function parseNid(v) {
        if (v.length !== 14) return;
        fetch('/api/members/parse-nid', {
            method: 'POST',
            headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
            body: JSON.stringify({national_id: v})
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.parsed && data.parsed.is_valid) {
                dobInput.value = data.parsed.dob;
                dobInput.style.background = '#ECFDF5';
                genderDisplay.value = data.parsed.gender;
                genderHidden.value = data.parsed.gender;
                genderDisplay.style.background = '#ECFDF5';
                nidStatus.style.display = 'block';
                nidStatus.style.color = '#059669';
                nidStatus.textContent = '✓ ' + data.parsed.governorate_name_ar + ' — ' + data.parsed.age_years + ' سنة';
            } else {
                nidStatus.style.display = 'block';
                nidStatus.style.color = '#DC2626';
                nidStatus.textContent = (data.parsed && data.parsed.errors) ? data.parsed.errors[0] : 'رقم قومي غير صالح';
            }
        });
    }

    if (nidInput) {
        nidInput.addEventListener('input', function() {
            var v = this.value.replace(/\D/g, '');
            this.value = v;
            if (v.length === 14) parseNid(v);
            else nidStatus.style.display = 'none';
        });
        if (nidInput.value.length === 14) parseNid(nidInput.value);
    }
});
</script>
<?php $__template->endSection(); ?>
