<?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 name="gender" 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="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 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>
                <select name="department_id" class="form-control">
                    <option value="">-- اختر --</option>
                    <?php foreach ($departments as $d): ?>
                    <option value="<?= (int) $d['id'] ?>" <?= (old('department_id') ?? ($isEdit ? $profile->department_id : '')) == $d['id'] ? 'selected' : '' ?>><?= e($d['name_ar']) ?></option>
                    <?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;">تاريخ التعيين <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>
                <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="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>
                <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>
                <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>
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(); ?>
