<?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', (string) ($defaultVat ?? 1))) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="1">
                <small style="color:#6B7280;">تُحتسب على الإيجار الشهري + المرافق</small>
            </div>

            <div></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 style="grid-column:1/-1;">
                <label class="form-label">طريقة المرافق</label>
                <select name="utilities_mode" id="utilities_mode" class="form-input" onchange="toggleUtilitiesMode()">
                    <?php foreach (($utilitiesModes ?? []) as $val => $label): ?>
                    <option value="<?= e($val) ?>" <?= old('utilities_mode', 'rent_pct') === $val ? 'selected' : '' ?>><?= e($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- نسبة من الإيجار -->
            <div id="utils_rent_pct_wrap" style="display:<?= in_array(old('utilities_mode','rent_pct'), ['rent_pct','both']) ? 'block' : 'none' ?>;">
                <label class="form-label">نسبة المرافق من الإيجار (%)</label>
                <input type="number" name="utilities_rent_pct" id="utilities_rent_pct" value="<?= e(old('utilities_rent_pct', '0')) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="0">
                <small style="color:#6B7280;">نسبة من الإيجار الشهري (السنة الأولى) مقابل المرافق</small>
            </div>

            <!-- نسبة من تكلفة المرفق -->
            <div id="utils_facility_pct_wrap" style="display:<?= in_array(old('utilities_mode','rent_pct'), ['facility_cost_pct','both']) ? 'block' : 'none' ?>;">
                <label class="form-label">نسبة المرافق من تكلفة المرفق (%)</label>
                <input type="number" name="utilities_facility_pct" id="utilities_facility_pct" value="<?= e(old('utilities_facility_pct', '0')) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="0">
            </div>

            <div id="facility_monthly_cost_wrap" style="display:<?= in_array(old('utilities_mode','rent_pct'), ['facility_cost_pct','both']) ? 'block' : 'none' ?>;">
                <label class="form-label">تكلفة المرفق الشهرية على النادي (ج)</label>
                <input type="number" name="facility_monthly_cost" id="facility_monthly_cost" value="<?= e(old('facility_monthly_cost', '')) ?>" class="form-input" step="0.01" min="0" placeholder="0">
            </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;">

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;margin-bottom:15px;">
                <div>
                    <label class="form-label">نوع الزيادة</label>
                    <select name="escalation_type" id="escalation_type" class="form-input" onchange="toggleEscalation()">
                        <?php foreach (($escalationTypes ?? []) as $val => $label): ?>
                        <option value="<?= e($val) ?>" <?= old('escalation_type', 'none') === $val ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Flat rate -->
                <div id="esc_flat_wrap" style="display:<?= old('escalation_type', 'none') === 'flat' ? 'block' : 'none' ?>;">
                    <label class="form-label">نسبة الزيادة السنوية (%)</label>
                    <input type="number" name="escalation_rate" id="escalation_rate" value="<?= e(old('escalation_rate', '0')) ?>" class="form-input" step="0.01" min="0" max="100" placeholder="0">
                    <small style="color:#6B7280;">تُطبق على الإيجار الشهري في بداية كل سنة</small>
                </div>
            </div>

            <!-- Tiered escalation table -->
            <div id="esc_tiered_wrap" style="display:<?= old('escalation_type', 'none') === 'tiered' ? 'block' : 'none' ?>;">
                <table style="width:100%;border-collapse:collapse;font-size:14px;" id="tiersTable">
                    <thead>
                        <tr style="background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                            <th style="padding:10px 12px;text-align:right;width:50px;">#</th>
                            <th style="padding:10px 12px;text-align:right;">المدة بالأشهر</th>
                            <th style="padding:10px 12px;text-align:right;">نسبة الزيادة السنوية (%)</th>
                            <th style="padding:10px 12px;text-align:center;width:80px;">حذف</th>
                        </tr>
                    </thead>
                    <tbody id="tiersBody">
                        <!-- rows injected by JS -->
                    </tbody>
                </table>
                <button type="button" onclick="addTierRow()" class="btn btn-outline" style="margin-top:10px;font-size:13px;padding:6px 14px;">
                    <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إضافة شريحة
                </button>
                <input type="hidden" name="escalation_tiers_json" id="escalation_tiers_json" value="<?= e(old('escalation_tiers_json', '[]')) ?>">
            </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="payment_due_day" id="payment_due_day" value="<?= e(old('payment_due_day', '5')) ?>" class="form-input" min="1" max="28" placeholder="5">
                <small id="due_window_hint" style="color:#6B7280;">نافذة السداد: من يوم 1 حتى يوم 5</small>
            </div>

            <div></div>

            <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="daily_bank" <?= old('late_fee_type', 'none') === 'daily_bank' ? '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 id="late_fee_bank_rate_wrap" style="display:<?= old('late_fee_type', 'none') === 'daily_bank' ? 'block' : 'none' ?>;">
                <label class="form-label">النسبة البنكية السنوية (%)</label>
                <input type="number" name="late_fee_bank_rate" id="late_fee_bank_rate" value="<?= e(old('late_fee_bank_rate', (string) ($bankRate ?? 27.25))) ?>" class="form-input" step="0.0001" min="0" placeholder="<?= e((string) ($bankRate ?? 27.25)) ?>">
                <small style="color:#6B7280;">النسبة السنوية المعتمدة ÷ 365 = نسبة يومية</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>
                <input type="number" name="grace_period_months" id="grace_period_months" value="<?= e(old('grace_period_months', '0')) ?>" class="form-input" min="0" placeholder="0">
                <small style="color:#6B7280;">عدد الأشهر الأولى بدون إيجار (إعفاء كامل)</small>
            </div>

            <div>
                <label class="form-label">غرامة الإنهاء المبكر (أشهر إيجار)</label>
                <input type="number" name="early_termination_months" id="early_termination_months" value="<?= e(old('early_termination_months', '0')) ?>" class="form-input" min="0" 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>

        <!-- Static summary (year 1 / flat) -->
        <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;">الإيجار الشهري (سنة 1)</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 10px;display:grid;grid-template-columns:1fr 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 style="font-size:12px;color:#6B7280;margin-bottom:4px;">أشهر الإعفاء / يوم الاستحقاق</div>
                <div id="preview_grace_due" style="font-size:16px;font-weight:600;color:#374151;">—</div>
            </div>
        </div>

        <!-- Escalation year-by-year breakdown (hidden when no escalation) -->
        <div id="escalation_breakdown_wrap" style="display:none;padding:0 20px 20px;">
            <div style="border-top:1px dashed #86EFAC;padding-top:15px;">
                <div style="font-size:13px;font-weight:600;color:#059669;margin-bottom:8px;">توزيع الإيجار السنوي مع الزيادة</div>
                <div id="escalation_breakdown_table" style="overflow-x:auto;"></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_rent_pct','utilities_facility_pct',
                 'facility_monthly_cost','deposit_percentage','start_date','end_date','payment_due_day',
                 'escalation_type','escalation_rate','grace_period_months','utilities_mode'];
    ids.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('input', calcPreview);
        if (el) el.addEventListener('change', calcPreview);
    });

    // Payment due day hint
    const dueDayEl = document.getElementById('payment_due_day');
    if (dueDayEl) {
        dueDayEl.addEventListener('input', function() {
            const v = parseInt(this.value) || 5;
            document.getElementById('due_window_hint').textContent = 'نافذة السداد: من يوم 1 حتى يوم ' + v;
        });
    }

    // Restore tiers from old input if present
    const tiersInput = document.getElementById('escalation_tiers_json');
    if (tiersInput && tiersInput.value && tiersInput.value !== '[]') {
        try {
            const tiers = JSON.parse(tiersInput.value);
            if (Array.isArray(tiers)) {
                tiers.forEach(t => addTierRow(t.months, t.annual_rate));
            }
        } catch(e) {}
    }

    calcPreview();
});

function toggleUtilitiesMode() {
    const mode = document.getElementById('utilities_mode').value;
    document.getElementById('utils_rent_pct_wrap').style.display       = ['rent_pct','both'].includes(mode) ? 'block' : 'none';
    document.getElementById('utils_facility_pct_wrap').style.display   = ['facility_cost_pct','both'].includes(mode) ? 'block' : 'none';
    document.getElementById('facility_monthly_cost_wrap').style.display = ['facility_cost_pct','both'].includes(mode) ? 'block' : 'none';
    calcPreview();
}

function toggleEscalation() {
    const type = document.getElementById('escalation_type').value;
    document.getElementById('esc_flat_wrap').style.display   = type === 'flat'   ? 'block' : 'none';
    document.getElementById('esc_tiered_wrap').style.display = type === 'tiered' ? 'block' : 'none';
    calcPreview();
}

function toggleLateFeeRate() {
    const type = document.getElementById('late_fee_type').value;
    document.getElementById('late_fee_rate_wrap').style.display      = ['daily','weekly','monthly'].includes(type) ? 'block' : 'none';
    document.getElementById('late_fee_bank_rate_wrap').style.display = type === 'daily_bank' ? 'block' : 'none';
    // map daily_bank → late_fee_type = daily + late_fee_bank_rate set
}

// Tiers table
let tierCount = 0;
function addTierRow(months, rate) {
    tierCount++;
    const tbody = document.getElementById('tiersBody');
    const tr = document.createElement('tr');
    tr.setAttribute('data-tier', tierCount);
    tr.style.borderBottom = '1px solid #F3F4F6';
    tr.innerHTML = `
        <td style="padding:8px 12px;color:#6B7280;">${tierCount}</td>
        <td style="padding:8px 12px;">
            <input type="number" class="form-input tier-months" min="1" value="${months || 12}" style="width:100px;" oninput="syncTiersJson()">
        </td>
        <td style="padding:8px 12px;">
            <input type="number" class="form-input tier-rate" min="0" max="100" step="0.01" value="${rate || 0}" style="width:120px;" oninput="syncTiersJson()">
        </td>
        <td style="padding:8px 12px;text-align:center;">
            <button type="button" onclick="removeTierRow(this)" style="background:none;border:none;color:#DC2626;cursor:pointer;">
                <i data-lucide="trash-2" style="width:14px;height:14px;"></i>
            </button>
        </td>
    `;
    tbody.appendChild(tr);
    if (typeof lucide !== 'undefined') lucide.createIcons();
    syncTiersJson();
    calcPreview();
}

function removeTierRow(btn) {
    btn.closest('tr').remove();
    // renumber
    document.querySelectorAll('#tiersBody tr').forEach((tr, i) => {
        tr.cells[0].textContent = i + 1;
    });
    tierCount = document.querySelectorAll('#tiersBody tr').length;
    syncTiersJson();
    calcPreview();
}

function syncTiersJson() {
    const rows = document.querySelectorAll('#tiersBody tr');
    const tiers = [];
    rows.forEach(row => {
        const months = parseInt(row.querySelector('.tier-months')?.value) || 12;
        const rate   = parseFloat(row.querySelector('.tier-rate')?.value) || 0;
        tiers.push({ months, annual_rate: rate });
    });
    document.getElementById('escalation_tiers_json').value = JSON.stringify(tiers);
    calcPreview();
}

function getCalcMonths(startVal, endVal) {
    if (!startVal || !endVal) return 1;
    const s = new Date(startVal), e = new Date(endVal);
    if (e <= s) return 1;
    const y = e.getFullYear() - s.getFullYear();
    const m = e.getMonth() - s.getMonth();
    const d = e.getDate() - s.getDate();
    return Math.max(1, y * 12 + m + (d > 0 ? 1 : 0));
}

function getEscalationMultiplier(monthIndex, escType, escRate, tiers) {
    if (escType === 'none' || escType === '') return 1.0;
    const yearIndex = Math.floor(monthIndex / 12);
    if (escType === 'flat') {
        return Math.pow(1 + escRate / 100, yearIndex);
    }
    if (escType === 'tiered') {
        let compound = 1.0;
        for (let y = 0; y < yearIndex; y++) {
            const yStart = y * 12;
            let cum = 0, rateForYear = 0;
            for (const tier of tiers) {
                cum += tier.months;
                if (yStart < cum) { rateForYear = tier.annual_rate; break; }
            }
            compound *= (1 + rateForYear / 100);
        }
        return compound;
    }
    return 1.0;
}

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 depositPct = parseFloat(document.getElementById('deposit_percentage')?.value) || 0;
    const startVal   = document.getElementById('start_date')?.value;
    const endVal     = document.getElementById('end_date')?.value;
    const graceMo    = parseInt(document.getElementById('grace_period_months')?.value) || 0;
    const dueDay     = parseInt(document.getElementById('payment_due_day')?.value) || 5;
    const escType    = document.getElementById('escalation_type')?.value || 'none';
    const escRate    = parseFloat(document.getElementById('escalation_rate')?.value) || 0;
    const utilsMode  = document.getElementById('utilities_mode')?.value || 'rent_pct';
    const utilsRentPct     = parseFloat(document.getElementById('utilities_rent_pct')?.value) || 0;
    const utilsFacPct      = parseFloat(document.getElementById('utilities_facility_pct')?.value) || 0;
    const facilityMonthly  = parseFloat(document.getElementById('facility_monthly_cost')?.value) || 0;

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

    const subtotal = units * rate;
    const months   = getCalcMonths(startVal, endVal);
    const baseMonthlyY1 = subtotal / months;

    // Tiers
    let tiers = [];
    try { tiers = JSON.parse(document.getElementById('escalation_tiers_json')?.value || '[]'); } catch(e) {}

    // Monthly utilities (year-1 base)
    let utilsRent = 0, utilsFac = 0;
    if (['rent_pct','both'].includes(utilsMode)) utilsRent = baseMonthlyY1 * (utilsRentPct / 100);
    if (['facility_cost_pct','both'].includes(utilsMode)) utilsFac = facilityMonthly * (utilsFacPct / 100);
    const monthlyUtils = utilsRent + utilsFac;

    // Year-1 monthly numbers (unescalated)
    const monthlyBase  = Math.round(baseMonthlyY1 * 100) / 100;
    const monthlyU     = Math.round(monthlyUtils * 100) / 100;
    const monthlyVat   = Math.round((monthlyBase + monthlyU) * (vatPct / 100) * 100) / 100;
    const monthlyTotal = Math.round((monthlyBase + monthlyU + monthlyVat) * 100) / 100;

    // Grand total (escalation-aware)
    let grandBase = 0;
    for (let m = 0; m < months; m++) {
        grandBase += baseMonthlyY1 * getEscalationMultiplier(m, escType, escRate, tiers);
    }
    const grandUtils = monthlyUtils * months;
    const grandVat   = (grandBase + grandUtils) * (vatPct / 100);
    const grandTotal = Math.round((grandBase + grandUtils + grandVat) * 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(monthlyU);
    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);
    document.getElementById('preview_grace_due').textContent = (graceMo > 0 ? graceMo + ' شهر إعفاء · ' : '') + 'استحقاق يوم ' + dueDay;

    // Year-by-year breakdown
    const breakdownWrap = document.getElementById('escalation_breakdown_wrap');
    if (escType !== 'none' && months > 1) {
        breakdownWrap.style.display = 'block';
        const totalYears = Math.ceil(months / 12);
        let html = '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
        html += '<thead><tr style="background:#DCFCE7;">' +
                '<th style="padding:7px 10px;text-align:right;">السنة</th>' +
                '<th style="padding:7px 10px;text-align:left;">إيجار شهري</th>' +
                '<th style="padding:7px 10px;text-align:left;">مرافق</th>' +
                '<th style="padding:7px 10px;text-align:left;">VAT</th>' +
                '<th style="padding:7px 10px;text-align:left;">إجمالي شهري</th>' +
                '</tr></thead><tbody>';
        for (let yr = 0; yr < totalYears; yr++) {
            const mult  = getEscalationMultiplier(yr * 12, escType, escRate, tiers);
            const b     = Math.round(baseMonthlyY1 * mult * 100) / 100;
            const u     = Math.round(monthlyUtils * 100) / 100;  // utils don't escalate in this model
            const v     = Math.round((b + u) * (vatPct / 100) * 100) / 100;
            const t     = Math.round((b + u + v) * 100) / 100;
            html += `<tr style="border-bottom:1px solid #F0FDF4;">
                <td style="padding:6px 10px;color:#6B7280;">سنة ${yr + 1}</td>
                <td style="padding:6px 10px;font-weight:600;color:#0D7377;">${fmt(b)}</td>
                <td style="padding:6px 10px;color:#7C3AED;">${fmt(u)}</td>
                <td style="padding:6px 10px;color:#D97706;">${fmt(v)}</td>
                <td style="padding:6px 10px;font-weight:700;color:#059669;">${fmt(t)}</td>
            </tr>`;
        }
        html += '</tbody></table>';
        document.getElementById('escalation_breakdown_table').innerHTML = html;
    } else {
        breakdownWrap.style.display = 'none';
    }
}

function clearPreview() {
    ['preview_base','preview_utils','preview_vat','preview_total','preview_months','preview_deposit','preview_grace_due']
        .forEach(id => { const el = document.getElementById(id); if (el) el.textContent = '—'; });
    document.getElementById('escalation_breakdown_wrap').style.display = 'none';
}

// Sync late_fee_type: daily_bank is a UI convenience — maps to type=daily + bank_rate set
// The server reads late_fee_type directly (accepts 'daily_bank' gracefully or
// the controller should map it). We'll let the form submit 'daily_bank' and handle it
// in the service by checking late_fee_bank_rate > 0 when type = 'daily'.
// Actually, map to 'daily' on submit for backward compat:
document.getElementById('contractForm')?.addEventListener('submit', function() {
    const typeEl = document.getElementById('late_fee_type');
    if (typeEl && typeEl.value === 'daily_bank') {
        typeEl.value = 'daily';
    }
});
</script>
<?php $__template->endSection(); ?>
