<?php
$__template->layout('Layout.main');
?>
<?php $__template->section('title'); ?>عقد تأجير جديد<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/rentals" class="btn btn-outline"><i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> العودة للعقود</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<form method="POST" action="/rentals/contracts" id="contractForm">
    <?= \App\Core\CSRF::field() ?>

    <!-- ── بيانات العقد ── -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;color:#0D7377;">بيانات العقد</h3>
        </div>
        <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">

            <div>
                <label class="form-label">الجهة المستأجرة <span style="color:#DC2626;">*</span></label>
                <select name="entity_id" class="form-input" required>
                    <option value="">-- اختر الجهة --</option>
                    <?php foreach ($entities as $ent): ?>
                    <option value="<?= (int) $ent['id'] ?>" <?= (string) old('entity_id') === (string) $ent['id'] ? 'selected' : '' ?>><?= e($ent['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label class="form-label">المرفق <span style="color:#DC2626;">*</span></label>
                <select name="facility_id" class="form-input" required>
                    <option value="">-- اختر المرفق --</option>
                    <?php foreach ($facilities as $fac): ?>
                    <option value="<?= (int) $fac['id'] ?>" <?= (string) old('facility_id') === (string) $fac['id'] ? 'selected' : '' ?>><?= e($fac['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label class="form-label">نوع النشاط</label>
                <select name="activity_type" class="form-input">
                    <option value="">-- اختر --</option>
                    <option value="practice"    <?= old('activity_type') === 'practice'    ? 'selected' : '' ?>>تدريب</option>
                    <option value="competitive" <?= old('activity_type') === 'competitive' ? 'selected' : '' ?>>تنافسي</option>
                </select>
            </div>

            <div>
                <label class="form-label">الفترة الزمنية</label>
                <select name="time_tier" class="form-input">
                    <option value="AM" <?= old('time_tier', 'AM') === 'AM' ? 'selected' : '' ?>>صباحي</option>
                    <option value="PM" <?= old('time_tier', 'AM') === 'PM' ? 'selected' : '' ?>>مسائي</option>
                </select>
            </div>

            <div>
                <label class="form-label">تاريخ البدء <span style="color:#DC2626;">*</span></label>
                <input type="date" name="start_date" id="start_date" value="<?= e(old('start_date')) ?>" class="form-input" required>
            </div>

            <div>
                <label class="form-label">تاريخ الانتهاء <span style="color:#DC2626;">*</span></label>
                <input type="date" name="end_date" id="end_date" value="<?= e(old('end_date')) ?>" class="form-input" required>
            </div>

            <div>
                <label class="form-label">عدد الوحدات <span style="color:#DC2626;">*</span></label>
                <input type="number" name="total_units" id="total_units" value="<?= e(old('total_units')) ?>" class="form-input" min="1" required>
            </div>

            <div>
                <label class="form-label">سعر الوحدة (جنيه) <span style="color:#DC2626;">*</span></label>
                <input type="number" name="unit_rate" id="unit_rate" value="<?= e(old('unit_rate')) ?>" class="form-input" step="0.01" min="0.01" required>
            </div>

            <div>
                <label class="form-label">نسبة التأمين (%)</label>
                <input type="number" name="deposit_percentage" id="deposit_percentage" value="<?= e(old('deposit_percentage', '10')) ?>" class="form-input" step="0.01" min="0" placeholder="10">
            </div>

            <div></div>

            <div style="grid-column:1/-1;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="2" style="resize:vertical;"><?= e(old('notes')) ?></textarea>
            </div>

        </div>
    </div>

    <!-- ── الرسوم الإضافية ── -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;color:#0D7377;">الرسوم الإضافية</h3>
        </div>
        <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">

            <div>
                <label class="form-label">نسبة القيمة المضافة (%)</label>
                <input type="number" name="vat_percentage" id="vat_percentage" value="<?= e(old('vat_percentage', '1')) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="1">
                <small style="color:#6B7280;">تُحتسب على الإيجار الشهري + المرافق</small>
            </div>

            <div>
                <label class="form-label">نسبة المرافق (%) — اختياري</label>
                <input type="number" name="utilities_percentage" id="utilities_percentage" value="<?= e(old('utilities_percentage', '0')) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="0">
                <small style="color:#6B7280;">نسبة من الإيجار الشهري مقابل المرافق</small>
            </div>

        </div>
    </div>

    <!-- ── غرامات التأخير ── -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
            <h3 style="margin:0;color:#0D7377;">غرامات التأخير</h3>
        </div>
        <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:15px;">

            <div>
                <label class="form-label">نوع الغرامة</label>
                <select name="late_fee_type" id="late_fee_type" class="form-input" onchange="toggleLateFeeRate()">
                    <option value="none"    <?= old('late_fee_type', 'none') === 'none'    ? 'selected' : '' ?>>لا يوجد</option>
                    <option value="daily"   <?= old('late_fee_type', 'none') === 'daily'   ? 'selected' : '' ?>>يومي</option>
                    <option value="weekly"  <?= old('late_fee_type', 'none') === 'weekly'  ? 'selected' : '' ?>>أسبوعي</option>
                    <option value="monthly" <?= old('late_fee_type', 'none') === 'monthly' ? 'selected' : '' ?>>شهري</option>
                </select>
            </div>

            <div id="late_fee_rate_wrap" style="display:<?= in_array(old('late_fee_type', 'none'), ['daily','weekly','monthly']) ? 'block' : 'none' ?>;">
                <label class="form-label">نسبة الغرامة (%)</label>
                <input type="number" name="late_fee_rate" id="late_fee_rate" value="<?= e(old('late_fee_rate', '0')) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="0">
                <small style="color:#6B7280;">% من إجمالي الفاتورة لكل فترة تأخير</small>
            </div>

        </div>
    </div>

    <!-- ── ملخص تقديري ── -->
    <div class="card" style="margin-bottom:20px;background:#F0FDF4;border:1px solid #BBF7D0;">
        <div style="padding:15px 20px;border-bottom:1px solid #BBF7D0;">
            <h3 style="margin:0;color:#059669;">ملخص الفاتورة الشهرية التقديري</h3>
        </div>
        <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:15px;text-align:center;">
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">الإيجار الشهري</div>
                <div id="preview_base" style="font-size:20px;font-weight:700;color:#0D7377;">—</div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">المرافق</div>
                <div id="preview_utils" style="font-size:20px;font-weight:700;color:#7C3AED;">—</div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">القيمة المضافة</div>
                <div id="preview_vat" style="font-size:20px;font-weight:700;color:#D97706;">—</div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">إجمالي الفاتورة</div>
                <div id="preview_total" style="font-size:20px;font-weight:700;color:#059669;">—</div>
            </div>
        </div>
        <div style="padding:0 20px 15px;display:grid;grid-template-columns:1fr 1fr;gap:15px;text-align:center;">
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">عدد الأشهر</div>
                <div id="preview_months" style="font-size:16px;font-weight:600;color:#374151;">—</div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">التأمين المطلوب</div>
                <div id="preview_deposit" style="font-size:16px;font-weight:600;color:#374151;">—</div>
            </div>
        </div>
    </div>

    <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary">إنشاء العقد</button>
        <a href="/rentals" class="btn btn-outline">إلغاء</a>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();

    const ids = ['total_units','unit_rate','vat_percentage','utilities_percentage','deposit_percentage','start_date','end_date'];
    ids.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('input', calcPreview);
    });
    calcPreview();
});

function toggleLateFeeRate() {
    const type = document.getElementById('late_fee_type').value;
    const wrap = document.getElementById('late_fee_rate_wrap');
    wrap.style.display = ['daily','weekly','monthly'].includes(type) ? 'block' : 'none';
}

function calcPreview() {
    const units       = parseFloat(document.getElementById('total_units')?.value) || 0;
    const rate        = parseFloat(document.getElementById('unit_rate')?.value) || 0;
    const vatPct      = parseFloat(document.getElementById('vat_percentage')?.value) || 1;
    const utilsPct    = parseFloat(document.getElementById('utilities_percentage')?.value) || 0;
    const depositPct  = parseFloat(document.getElementById('deposit_percentage')?.value) || 0;
    const startVal    = document.getElementById('start_date')?.value;
    const endVal      = document.getElementById('end_date')?.value;

    if (!units || !rate) { clearPreview(); return; }

    const subtotal = units * rate;

    let months = 1;
    if (startVal && endVal) {
        const s = new Date(startVal), e = new Date(endVal);
        if (e > s) {
            const diffMs   = e - s;
            const diffDays = diffMs / (1000 * 60 * 60 * 24);
            months = Math.max(1, Math.ceil(diffDays / 30));
        }
    }

    const monthlyBase   = Math.round((subtotal / months) * 100) / 100;
    const monthlyUtils  = Math.round(monthlyBase * (utilsPct / 100) * 100) / 100;
    const monthlyVat    = Math.round((monthlyBase + monthlyUtils) * (vatPct / 100) * 100) / 100;
    const monthlyTotal  = Math.round((monthlyBase + monthlyUtils + monthlyVat) * 100) / 100;

    const totalWithUtils = subtotal + (subtotal * utilsPct / 100);
    const totalVat       = subtotal * (vatPct / 100);
    const grandTotal     = Math.round((subtotal + subtotal * utilsPct / 100 + totalVat) * 100) / 100;
    const deposit        = Math.round(grandTotal * (depositPct / 100) * 100) / 100;

    const fmt = v => v.toLocaleString('ar-EG', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ج';

    document.getElementById('preview_base').textContent    = fmt(monthlyBase);
    document.getElementById('preview_utils').textContent   = fmt(monthlyUtils);
    document.getElementById('preview_vat').textContent     = fmt(monthlyVat);
    document.getElementById('preview_total').textContent   = fmt(monthlyTotal);
    document.getElementById('preview_months').textContent  = months + ' شهر';
    document.getElementById('preview_deposit').textContent = fmt(deposit);
}

function clearPreview() {
    ['preview_base','preview_utils','preview_vat','preview_total','preview_months','preview_deposit']
        .forEach(id => { document.getElementById(id).textContent = '—'; });
}
</script>
<?php $__template->endSection(); ?>
