<?php $__template->layout('Layout.main'); ?>
<?php $isEdit = $contract !== null; ?>
<?php $__template->section('title'); ?><?= $isEdit ? 'تعديل العقد' : 'إنشاء عقد جديد' ?><?php $__template->endSection(); ?>

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

<?php $__template->section('content'); ?>
<form method="POST" action="<?= $isEdit ? '/hr/contracts/' . (int) $contract->id : '/hr/contracts' ?>">
    <?= csrf_field() ?>
    <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(250px,1fr));gap:16px;">
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">الموظف <span style="color:#DC2626;">*</span></label>
                <?php if ($isEdit): ?>
                    <input type="text" class="form-control" value="<?= $profile ? e($profile->first_name_ar . ' ' . $profile->last_name_ar) : '' ?>" readonly style="background:#f3f4f6;">
                <?php elseif ($profile): ?>
                    <input type="hidden" name="employee_profile_id" value="<?= (int) $profile->id ?>">
                    <input type="text" class="form-control" value="<?= e($profile->first_name_ar . ' ' . $profile->last_name_ar) ?>" readonly style="background:#f3f4f6;">
                <?php else: ?>
                    <input type="hidden" name="employee_profile_id" id="employee_profile_id" value="<?= (int) old('employee_profile_id') ?>">
                    <div style="position:relative;">
                        <input type="text" class="form-control" id="employee_search" placeholder="ابحث باسم الموظف..." autocomplete="off">
                        <div id="employee_results" style="position:absolute;top:100%;right:0;left:0;z-index:100;background:#fff;border:1px solid #ddd;border-top:none;max-height:200px;overflow-y:auto;display:none;"></div>
                    </div>
                <?php endif; ?>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">نوع العقد <span style="color:#DC2626;">*</span></label>
                <select name="contract_type" class="form-control" required>
                    <option value="definite" <?= (old('contract_type') ?? ($isEdit ? $contract->contract_type : '')) === 'definite' ? 'selected' : '' ?>>محدد المدة</option>
                    <option value="indefinite" <?= (old('contract_type') ?? ($isEdit ? $contract->contract_type : '')) === 'indefinite' ? 'selected' : '' ?>>غير محدد المدة</option>
                </select>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">تاريخ البداية <span style="color:#DC2626;">*</span></label>
                <input type="date" name="start_date" value="<?= e(old('start_date') ?? ($isEdit ? $contract->start_date : '')) ?>" class="form-control" required>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">تاريخ النهاية</label>
                <input type="date" name="end_date" value="<?= e(old('end_date') ?? ($isEdit ? $contract->end_date : '')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">فترة الاختبار (أشهر)</label>
                <input type="number" name="probation_months" value="<?= e(old('probation_months') ?? ($isEdit ? $contract->probation_months : '3')) ?>" class="form-control" min="0" max="3">
                <small style="color:#6B7280;">الحد الأقصى 3 أشهر (مادة 33)</small>
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">ساعات العمل اليومية</label>
                <input type="text" name="working_hours_per_day" value="<?= e(old('working_hours_per_day') ?? ($isEdit ? $contract->working_hours_per_day : '8')) ?>" class="form-control">
            </div>
            <div>
                <label style="display:block;margin-bottom:4px;font-size:13px;">فترة الإنذار (أشهر)</label>
                <input type="number" name="notice_period_months" value="<?= e(old('notice_period_months') ?? ($isEdit ? $contract->notice_period_months : '2')) ?>" class="form-control" min="0">
            </div>
            <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 ? $contract->basic_salary : ($profile ? $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;">إجمالي الحزمة <span style="color:#DC2626;">*</span></label>
                <input type="number" name="total_package" value="<?= e(old('total_package') ?? ($isEdit ? $contract->total_package : ($profile ? $profile->basic_salary : '0.00'))) ?>" class="form-control" step="0.01" min="0" required>
                <small style="color:#6B7280;">الراتب الأساسي + البدلات</small>
            </div>
            <div style="grid-column:1/-1;">
                <label style="display:block;margin-bottom:4px;font-size:13px;">شروط العقد</label>
                <textarea name="terms_ar" class="form-control" rows="4"><?= e(old('terms_ar') ?? ($isEdit ? json_decode($contract->terms_json ?? 'null', true) ?? '' : '')) ?></textarea>
            </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="2"><?= e(old('notes') ?? ($isEdit ? $contract->notes : '')) ?></textarea>
            </div>
        </div>
    </div>
    <div style="display:flex;gap:10px;justify-content:flex-end;">
        <a href="/hr/contracts" class="btn btn-secondary">إلغاء</a>
        <button type="submit" class="btn btn-primary"><?= $isEdit ? 'تحديث' : 'حفظ' ?></button>
    </div>
</form>

<?php if (!$isEdit && !$profile): ?>
<script>
(function() {
    var searchInput = document.getElementById('employee_search');
    var resultsDiv = document.getElementById('employee_results');
    var hiddenInput = document.getElementById('employee_profile_id');
    var timer = null;

    if (!searchInput) return;

    searchInput.addEventListener('input', function() {
        clearTimeout(timer);
        var q = this.value.trim();
        if (q.length < 2) { resultsDiv.style.display = 'none'; return; }
        timer = setTimeout(function() {
            fetch('/hr/employees/search-json?q=' + encodeURIComponent(q))
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (!data.length) {
                        resultsDiv.innerHTML = '<div style="padding:10px;color:#9CA3AF;text-align:center;">لا توجد نتائج</div>';
                    } else {
                        resultsDiv.innerHTML = data.map(function(emp) {
                            return '<div class="emp-option" data-id="' + emp.id + '" style="padding:8px 12px;cursor:pointer;border-bottom:1px solid #f0f0f0;" onmouseover="this.style.background=\'#f3f4f6\'" onmouseout="this.style.background=\'#fff\'">'
                                + escapeHtml(emp.first_name_ar + ' ' + emp.last_name_ar)
                                + ' <small style="color:#6B7280;">(' + escapeHtml(emp.employee_number || '') + ')</small></div>';
                        }).join('');
                    }
                    resultsDiv.style.display = 'block';
                });
        }, 300);
    });

    resultsDiv.addEventListener('click', function(e) {
        var option = e.target.closest('.emp-option');
        if (option) {
            hiddenInput.value = option.getAttribute('data-id');
            searchInput.value = option.textContent.trim();
            resultsDiv.style.display = 'none';
        }
    });

    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !resultsDiv.contains(e.target)) {
            resultsDiv.style.display = 'none';
        }
    });

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }
})();
</script>
<?php endif; ?>
<?php $__template->endSection(); ?>
