<?php
/** @var array $grouped */
/** @var array $annualRates */
/** @var array $membershipPrices */
use App\Modules\Pricing\Services\RuleFieldMapper;

$__template->layout('Layout.main');
$__template->section('title'); ?>لوحة التسعير<?php $__template->endSection(); ?>

<?php $__template->section('styles'); ?>
<style>
.pricing-dashboard { display:flex; flex-direction:column; gap:20px; }

.pricing-section {
    background:#fff;
    border-radius:12px;
    border:1px solid #E5E7EB;
    overflow:hidden;
    transition:box-shadow .2s;
}
.pricing-section:hover { box-shadow:0 4px 12px rgba(0,0,0,.06); }

.pricing-section-header {
    padding:18px 24px;
    display:flex;
    align-items:center;
    gap:14px;
    cursor:pointer;
    user-select:none;
    border-bottom:1px solid transparent;
    transition:border-color .2s;
}
.pricing-section.open .pricing-section-header { border-bottom-color:#E5E7EB; }

.pricing-section-icon {
    width:42px; height:42px;
    border-radius:10px;
    display:flex; align-items:center; justify-content:center;
    font-size:20px;
    flex-shrink:0;
}

.pricing-section-title {
    flex:1;
}
.pricing-section-title h3 { margin:0; font-size:16px; font-weight:700; color:#1F2937; }
.pricing-section-title p { margin:2px 0 0; font-size:13px; color:#6B7280; }

.pricing-section-badge {
    background:#F3F4F6; border-radius:20px; padding:4px 12px;
    font-size:12px; color:#6B7280; font-weight:600;
}
.pricing-section-badge.dirty { background:#FEF3C7; color:#D97706; }

.pricing-section-chevron {
    width:20px; height:20px; transition:transform .2s;
    color:#9CA3AF;
}
.pricing-section.open .pricing-section-chevron { transform:rotate(180deg); }

.pricing-section-body {
    display:none;
    padding:24px;
}
.pricing-section.open .pricing-section-body { display:block; }

.pricing-fields-grid {
    display:grid;
    grid-template-columns:repeat(auto-fill, minmax(260px, 1fr));
    gap:18px;
}

.pricing-rule-card {
    background:#F9FAFB;
    border:1px solid #E5E7EB;
    border-radius:10px;
    padding:14px 16px;
}
.pricing-rule-card-title {
    font-size:13px; font-weight:600; color:#374151;
    margin-bottom:10px; padding-bottom:8px;
    border-bottom:1px solid #E5E7EB;
}

.pricing-input-group {
    display:flex;
    flex-direction:column;
    gap:4px;
    margin-bottom:10px;
}
.pricing-input-group:last-child { margin-bottom:0; }

.pricing-input-label {
    font-size:12px; color:#6B7280; font-weight:500;
}

.pricing-input-wrap {
    display:flex; align-items:center; gap:6px;
}

.pricing-input {
    flex:1;
    padding:8px 12px;
    border:1px solid #D1D5DB;
    border-radius:8px;
    font-size:14px;
    font-weight:600;
    background:#fff;
    transition:border-color .15s, box-shadow .15s;
    min-width:0;
}
.pricing-input:focus {
    outline:none;
    border-color:#0D7377;
    box-shadow:0 0 0 3px rgba(13,115,119,.1);
}
.pricing-input.dirty {
    border-color:#D97706;
    background:#FFFBEB;
}

.pricing-input-suffix {
    background:#F3F4F6;
    border:1px solid #E5E7EB;
    padding:8px 10px;
    border-radius:8px;
    font-size:12px;
    color:#6B7280;
    font-weight:600;
    white-space:nowrap;
}

.pricing-section-footer {
    padding:16px 24px;
    border-top:1px solid #E5E7EB;
    display:flex;
    align-items:center;
    gap:12px;
    background:#F9FAFB;
}
.pricing-section-footer textarea {
    flex:1;
    padding:8px 12px;
    border:1px solid #D1D5DB;
    border-radius:8px;
    font-size:13px;
    resize:none;
    height:36px;
}

.toggle-switch { position:relative; display:inline-block; width:44px; height:24px; }
.toggle-switch input { opacity:0; width:0; height:0; }
.toggle-slider {
    position:absolute; cursor:pointer; inset:0;
    background:#D1D5DB; border-radius:24px; transition:.2s;
}
.toggle-slider:before {
    content:""; position:absolute; height:18px; width:18px;
    right:3px; bottom:3px; background:#fff; border-radius:50%; transition:.2s;
}
.toggle-switch input:checked + .toggle-slider { background:#0D7377; }
.toggle-switch input:checked + .toggle-slider:before { transform:translateX(-20px); }

/* Annual rates */
.annual-tabs { display:flex; gap:8px; margin-bottom:16px; flex-wrap:wrap; }
.annual-tab {
    padding:8px 16px; border-radius:8px; font-size:13px; font-weight:600;
    border:1px solid #E5E7EB; background:#fff; cursor:pointer; transition:.15s;
}
.annual-tab.active { background:#0D7377; color:#fff; border-color:#0D7377; }
.annual-tab:hover:not(.active) { background:#F3F4F6; }

.annual-panel { display:none; }
.annual-panel.active { display:grid; grid-template-columns:repeat(auto-fill, minmax(200px, 1fr)); gap:14px; }

.membership-prices-grid {
    display:grid;
    grid-template-columns:repeat(auto-fill, minmax(240px, 1fr));
    gap:14px;
}
.membership-price-card {
    background:#F9FAFB; border:1px solid #E5E7EB; border-radius:10px; padding:14px 16px;
}
.membership-price-card h4 { margin:0 0 8px; font-size:13px; color:#374151; font-weight:600; }

.btn-save-section {
    padding:8px 20px; border-radius:8px; font-size:13px; font-weight:600;
    background:#0D7377; color:#fff; border:none; cursor:pointer;
    transition:background .15s;
}
.btn-save-section:hover { background:#0A5F62; }
.btn-save-section:disabled { background:#D1D5DB; cursor:not-allowed; }

.add-year-form {
    display:flex; gap:10px; align-items:end; flex-wrap:wrap;
    margin-top:16px; padding-top:16px; border-top:1px solid #E5E7EB;
}
.add-year-form .form-group { display:flex; flex-direction:column; gap:4px; }
.add-year-form label { font-size:12px; color:#6B7280; font-weight:500; }
.add-year-form input { padding:8px 12px; border:1px solid #D1D5DB; border-radius:8px; font-size:14px; width:100px; }

.toast-msg {
    position:fixed; top:20px; left:50%; transform:translateX(-50%);
    padding:12px 24px; border-radius:10px; font-size:14px; font-weight:600;
    z-index:9999; animation:slideDown .3s ease;
    box-shadow:0 4px 20px rgba(0,0,0,.15);
}
.toast-msg.success { background:#059669; color:#fff; }
.toast-msg.error { background:#DC2626; color:#fff; }
@keyframes slideDown { from { opacity:0; transform:translateX(-50%) translateY(-10px); } to { opacity:1; transform:translateX(-50%) translateY(0); } }

/* Versioning UI */
.btn-versions {
    background:none; border:1px solid #D1D5DB; border-radius:6px;
    padding:3px 8px; font-size:11px; color:#6B7280; cursor:pointer;
    transition:.15s; display:inline-flex; align-items:center; gap:4px;
    margin-top:8px;
}
.btn-versions:hover { background:#F3F4F6; color:#374151; border-color:#9CA3AF; }
.btn-versions svg { width:12px; height:12px; }

.version-modal-overlay {
    position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:10000;
    display:flex; align-items:center; justify-content:center;
    animation:fadeIn .2s;
}
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
.version-modal {
    background:#fff; border-radius:14px; width:90%; max-width:640px;
    max-height:80vh; overflow:hidden; display:flex; flex-direction:column;
    box-shadow:0 20px 60px rgba(0,0,0,.2);
}
.version-modal-header {
    padding:18px 24px; border-bottom:1px solid #E5E7EB;
    display:flex; align-items:center; gap:12px;
}
.version-modal-header h3 { flex:1; margin:0; font-size:16px; color:#1F2937; }
.version-modal-close { background:none; border:none; cursor:pointer; font-size:20px; color:#9CA3AF; padding:4px; }
.version-modal-close:hover { color:#1F2937; }

.version-modal-body { padding:20px 24px; overflow-y:auto; flex:1; }

.version-timeline { display:flex; flex-direction:column; gap:12px; }
.version-item {
    display:flex; gap:12px; padding:12px 14px;
    background:#F9FAFB; border:1px solid #E5E7EB; border-radius:10px;
}
.version-item.current { border-color:#0D7377; background:rgba(13,115,119,.04); }
.version-dot {
    width:10px; height:10px; border-radius:50%; margin-top:4px; flex-shrink:0;
    background:#D1D5DB;
}
.version-item.current .version-dot { background:#0D7377; }
.version-info { flex:1; min-width:0; }
.version-dates { font-size:12px; color:#6B7280; margin-bottom:4px; }
.version-value { font-size:13px; color:#374151; font-weight:500; direction:ltr; text-align:right; word-break:break-all; }
.version-badge { font-size:10px; background:#0D7377; color:#fff; padding:2px 8px; border-radius:4px; font-weight:600; }

.version-add-form {
    margin-top:16px; padding-top:16px; border-top:1px solid #E5E7EB;
}
.version-add-form h4 { font-size:14px; color:#374151; margin:0 0 12px; font-weight:600; }
.version-form-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:12px; }
.version-form-grid .form-group { display:flex; flex-direction:column; gap:4px; }
.version-form-grid label { font-size:12px; color:#6B7280; font-weight:500; }
.version-form-grid input, .version-form-grid textarea {
    padding:8px 12px; border:1px solid #D1D5DB; border-radius:8px; font-size:13px;
}
.version-form-grid textarea { grid-column:1/-1; resize:none; height:60px; }
.btn-add-version {
    padding:8px 16px; border-radius:8px; font-size:13px; font-weight:600;
    background:#2563EB; color:#fff; border:none; cursor:pointer;
}
.btn-add-version:hover { background:#1D4ED8; }
</style>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>
<div class="pricing-dashboard">

    <!-- Annual Rates Section -->
    <div class="pricing-section open">
        <div class="pricing-section-header" onclick="toggleSection(this)">
            <div class="pricing-section-icon" style="background:rgba(5,150,105,.1);">📊</div>
            <div class="pricing-section-title">
                <h3>الاشتراكات السنوية</h3>
                <p>أسعار الاشتراك السنوي لكل فئة حسب السنة المالية</p>
            </div>
            <span class="pricing-section-badge"><?= count($annualRates) ?> سنة</span>
            <svg class="pricing-section-chevron" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"/></svg>
        </div>
        <div class="pricing-section-body">
            <form method="POST" action="/pricing/annual-rates" class="section-form" data-section="annual-rates">
                <?= csrf_field() ?>
                <div class="annual-tabs">
                    <?php $first = true; foreach ($annualRates as $yearKey => $types): ?>
                        <?php $label = $yearKey === 'current' ? 'الحالي' : $yearKey . '/' . ((int)$yearKey + 1); ?>
                        <div class="annual-tab <?= $first ? 'active' : '' ?>" onclick="switchTab(this, '<?= e($yearKey) ?>')"><?= $label ?></div>
                    <?php $first = false; endforeach; ?>
                </div>

                <?php $first = true; foreach ($annualRates as $yearKey => $types): ?>
                <div class="annual-panel <?= $first ? 'active' : '' ?>" data-year="<?= e($yearKey) ?>">
                    <?php
                    $typeLabels = ['member' => 'العضو', 'spouse' => 'الزوج/ة', 'child' => 'الابن/البنت', 'temp' => 'المؤقت'];
                    foreach ($typeLabels as $typeKey => $typeLabel):
                        $row = $types[$typeKey] ?? null;
                        if (!$row) continue;
                    ?>
                    <div class="pricing-rule-card">
                        <div class="pricing-rule-card-title"><?= $typeLabel ?></div>
                        <div class="pricing-input-group">
                            <label class="pricing-input-label">الاشتراك السنوي</label>
                            <div class="pricing-input-wrap">
                                <input type="number" name="rate[<?= (int)$row['id'] ?>]" value="<?= e($row['base_amount']) ?>" step="0.01" class="pricing-input" dir="ltr">
                                <span class="pricing-input-suffix">ج.م</span>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php $first = false; endforeach; ?>

                <?php
                $devFeeData = \App\Modules\Rules\Services\RuleEngine::get('DEVELOPMENT_FEE');
                $devFee = $devFeeData['amount'] ?? '35.00';
                ?>
                <div style="margin-top:14px;">
                    <div class="pricing-rule-card" style="max-width:260px;">
                        <div class="pricing-rule-card-title">رسم التنمية (يُضاف لكل اشتراك)</div>
                        <div class="pricing-input-group">
                            <div class="pricing-input-wrap">
                                <input type="number" name="dev_fee" value="<?= e($devFee) ?>" step="0.01" class="pricing-input" dir="ltr">
                                <span class="pricing-input-suffix">ج.م</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="pricing-section-footer" style="margin-top:16px;padding:16px 0;border-top:1px solid #E5E7EB;background:transparent;">
                    <textarea name="change_reason" placeholder="سبب التعديل..." style="flex:1;"></textarea>
                    <button type="submit" class="btn-save-section">حفظ الاشتراكات</button>
                </div>
            </form>

            <form method="POST" action="/pricing/annual-rates/add-year" class="add-year-form">
                <?= csrf_field() ?>
                <div class="form-group">
                    <label>سنة مالية جديدة (تبدأ يوليو)</label>
                    <input type="number" name="year" placeholder="<?= date('Y') ?>" min="2020" max="2040" required>
                </div>
                <div class="form-group">
                    <label>عضو</label>
                    <input type="number" name="member_rate" value="492" step="0.01">
                </div>
                <div class="form-group">
                    <label>زوج/ة</label>
                    <input type="number" name="spouse_rate" value="492" step="0.01">
                </div>
                <div class="form-group">
                    <label>ابن</label>
                    <input type="number" name="child_rate" value="222" step="0.01">
                </div>
                <div class="form-group">
                    <label>مؤقت</label>
                    <input type="number" name="temp_rate" value="222" step="0.01">
                </div>
                <button type="submit" class="btn-save-section" style="background:#2563EB;">+ إضافة سنة</button>
            </form>
        </div>
    </div>

    <!-- Late Payment Penalty Schedule -->
    <div class="pricing-section">
        <div class="pricing-section-header" onclick="toggleSection(this)">
            <div class="pricing-section-icon" style="background:rgba(220,38,38,.1);">⚠️</div>
            <div class="pricing-section-title">
                <h3>جدول غرامات التأخير عن سداد الاشتراك السنوي</h3>
                <p>طبقاً للائحة — الموعد الأقصى للسداد: نهاية سبتمبر من كل عام</p>
            </div>
            <svg class="pricing-section-chevron" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"/></svg>
        </div>
        <div class="pricing-section-body">
            <table style="width:100%;border-collapse:collapse;font-size:14px;">
                <thead>
                    <tr style="background:#FEF2F2;border-bottom:2px solid #FECACA;">
                        <th style="padding:12px 16px;text-align:right;font-weight:700;color:#991B1B;">الفترة</th>
                        <th style="padding:12px 16px;text-align:center;font-weight:700;color:#991B1B;">نسبة الغرامة</th>
                        <th style="padding:12px 16px;text-align:right;font-weight:700;color:#991B1B;">ملاحظات</th>
                    </tr>
                </thead>
                <tbody>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:10px 16px;">من أول أكتوبر حتى نهاية يونيو</td>
                        <td style="padding:10px 16px;text-align:center;font-weight:700;color:#DC2626;">10%</td>
                        <td style="padding:10px 16px;color:#6B7280;">من قيمة إجمالي الاشتراك</td>
                    </tr>
                    <tr style="border-bottom:1px solid #F3F4F6;background:#FAFAFA;">
                        <td style="padding:10px 16px;">السنة المالية الأولى</td>
                        <td style="padding:10px 16px;text-align:center;font-weight:700;color:#DC2626;">50%</td>
                        <td style="padding:10px 16px;color:#6B7280;">من قيمة إجمالي الاشتراك السنوي</td>
                    </tr>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:10px 16px;">السنة المالية الثانية</td>
                        <td style="padding:10px 16px;text-align:center;font-weight:700;color:#DC2626;">100%</td>
                        <td style="padding:10px 16px;color:#6B7280;">من قيمة إجمالي الاشتراك السنوي</td>
                    </tr>
                    <tr style="border-bottom:1px solid #F3F4F6;background:#FAFAFA;">
                        <td style="padding:10px 16px;">السنة المالية الثالثة</td>
                        <td style="padding:10px 16px;text-align:center;font-weight:700;color:#DC2626;">200%</td>
                        <td style="padding:10px 16px;color:#6B7280;">من قيمة إجمالي الاشتراك السنوي</td>
                    </tr>
                    <tr style="border-bottom:1px solid #F3F4F6;">
                        <td style="padding:10px 16px;">السنة المالية الرابعة</td>
                        <td style="padding:10px 16px;text-align:center;font-weight:700;color:#DC2626;">300%</td>
                        <td style="padding:10px 16px;color:#6B7280;">من قيمة إجمالي الاشتراك السنوي</td>
                    </tr>
                    <tr style="background:#FEF2F2;">
                        <td style="padding:10px 16px;font-weight:700;color:#991B1B;">السنة المالية الخامسة</td>
                        <td style="padding:10px 16px;text-align:center;font-weight:700;color:#991B1B;">إسقاط</td>
                        <td style="padding:10px 16px;color:#991B1B;">تُسقط العضوية طبقاً للائحة</td>
                    </tr>
                </tbody>
            </table>
            <div style="margin-top:12px;padding:12px 16px;background:#EFF6FF;border-radius:8px;border:1px solid #BFDBFE;font-size:13px;color:#1E40AF;">
                <strong>ملاحظة:</strong> يحق لمجلس الأمناء مد فترة الاشتراك السنوي شهر بدون غرامة.
            </div>
        </div>
    </div>

    <!-- Membership Prices Section -->
    <?php if (!empty($membershipPrices)): ?>
    <div class="pricing-section">
        <div class="pricing-section-header" onclick="toggleSection(this)">
            <div class="pricing-section-icon" style="background:rgba(99,102,241,.1);">🏠</div>
            <div class="pricing-section-title">
                <h3>أسعار العضويات</h3>
                <p>قيمة العضوية حسب المؤهل والفترة</p>
            </div>
            <span class="pricing-section-badge"><?= count($membershipPrices) ?></span>
            <svg class="pricing-section-chevron" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"/></svg>
        </div>
        <div class="pricing-section-body">
            <form method="POST" action="/pricing/membership-prices" class="section-form" data-section="membership-prices">
                <?= csrf_field() ?>
                <div class="membership-prices-grid">
                    <?php foreach ($membershipPrices as $mp): ?>
                    <div class="membership-price-card">
                        <h4><?= e($mp['name_ar']) ?></h4>
                        <div class="pricing-input-group">
                            <label class="pricing-input-label">من <?= e($mp['effective_from']) ?><?= $mp['effective_to'] ? ' إلى ' . e($mp['effective_to']) : ' (ساري)' ?></label>
                            <div class="pricing-input-wrap">
                                <input type="number" name="price[<?= (int)$mp['id'] ?>]" value="<?= e($mp['base_amount']) ?>" step="0.01" class="pricing-input" dir="ltr">
                                <span class="pricing-input-suffix">ج.م</span>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="pricing-section-footer" style="margin-top:16px;padding:16px 0;border-top:1px solid #E5E7EB;background:transparent;">
                    <textarea name="change_reason" placeholder="سبب التعديل..." style="flex:1;"></textarea>
                    <button type="submit" class="btn-save-section">حفظ أسعار العضويات</button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <!-- Business Rules Sections -->
    <?php foreach ($grouped as $category => $data): ?>
    <div class="pricing-section">
        <div class="pricing-section-header" onclick="toggleSection(this)">
            <div class="pricing-section-icon" style="background:<?= e($data['meta']['color']) ?>15;"><?= $data['meta']['icon'] ?></div>
            <div class="pricing-section-title">
                <h3><?= e($data['meta']['label']) ?></h3>
                <p><?= e($data['meta']['description']) ?></p>
            </div>
            <span class="pricing-section-badge"><?= count($data['rules']) ?></span>
            <svg class="pricing-section-chevron" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"/></svg>
        </div>
        <div class="pricing-section-body">
            <form method="POST" action="/pricing/section/<?= e($category) ?>" class="section-form" data-section="<?= e($category) ?>">
                <?= csrf_field() ?>
                <div class="pricing-fields-grid">
                    <?php foreach ($data['rules'] as $rule): ?>
                    <div class="pricing-rule-card">
                        <div class="pricing-rule-card-title"><?= e($rule['name_ar'] ?: $rule['rule_code']) ?></div>
                        <?= RuleFieldMapper::renderFields($rule) ?>
                        <button type="button" class="btn-versions" onclick="openVersions('<?= e($rule['rule_code']) ?>', '<?= e($rule['name_ar'] ?: $rule['rule_code']) ?>')">
                            <svg viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"/></svg>
                            النسخ التاريخية
                        </button>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="pricing-section-footer">
                    <textarea name="change_reason" placeholder="سبب التعديل..."></textarea>
                    <button type="submit" class="btn-save-section">حفظ <?= e($data['meta']['label']) ?></button>
                </div>
            </form>
        </div>
    </div>
    <?php endforeach; ?>

</div>
<?php $__template->endSection(); ?>

<?php $__template->section('scripts'); ?>
<script>
function toggleSection(header) {
    header.closest('.pricing-section').classList.toggle('open');
}

function switchTab(tab, yearKey) {
    var container = tab.closest('.pricing-section-body');
    container.querySelectorAll('.annual-tab').forEach(function(t) { t.classList.remove('active'); });
    container.querySelectorAll('.annual-panel').forEach(function(p) { p.classList.remove('active'); });
    tab.classList.add('active');
    container.querySelector('.annual-panel[data-year="' + yearKey + '"]').classList.add('active');
}

function showToast(message, type) {
    var el = document.createElement('div');
    el.className = 'toast-msg ' + type;
    el.textContent = message;
    document.body.appendChild(el);
    setTimeout(function() { el.remove(); }, 3000);
}

document.querySelectorAll('.section-form').forEach(function(form) {
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        var btn = form.querySelector('.btn-save-section');
        btn.disabled = true;
        btn.textContent = 'جاري الحفظ...';

        var formData = new FormData(form);

        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            btn.disabled = false;
            btn.textContent = btn.textContent.replace('جاري الحفظ...', '');
            if (data.success) {
                showToast('تم الحفظ بنجاح — ' + (data.updated || 0) + ' تعديل', 'success');
                form.querySelectorAll('.pricing-input.dirty').forEach(function(i) { i.classList.remove('dirty'); });
                btn.textContent = form.closest('.pricing-section').querySelector('h3').textContent.replace(/.*/, 'حفظ $&');
            } else {
                showToast(data.error || 'حدث خطأ', 'error');
            }
        })
        .catch(function() {
            btn.disabled = false;
            showToast('فشل الاتصال بالخادم', 'error');
        });

        // Restore button text
        var sectionTitle = form.closest('.pricing-section').querySelector('h3');
        setTimeout(function() {
            if (btn.textContent === 'جاري الحفظ...') {
                btn.textContent = 'حفظ ' + (sectionTitle ? sectionTitle.textContent : '');
            }
        }, 100);
    });
});

// Dirty state tracking
document.querySelectorAll('.pricing-input').forEach(function(input) {
    var original = input.value;
    input.addEventListener('input', function() {
        if (this.value !== original) {
            this.classList.add('dirty');
        } else {
            this.classList.remove('dirty');
        }
    });
});

// Versioning modal
function openVersions(ruleCode, ruleName) {
    var overlay = document.createElement('div');
    overlay.className = 'version-modal-overlay';
    overlay.onclick = function(e) { if (e.target === overlay) overlay.remove(); };
    overlay.innerHTML = '<div class="version-modal">' +
        '<div class="version-modal-header">' +
            '<h3>النسخ التاريخية — ' + ruleName + '</h3>' +
            '<button class="version-modal-close" onclick="this.closest(\'.version-modal-overlay\').remove()">&times;</button>' +
        '</div>' +
        '<div class="version-modal-body"><div style="text-align:center;color:#9CA3AF;padding:20px;">جاري التحميل...</div></div>' +
    '</div>';
    document.body.appendChild(overlay);

    fetch('/pricing/rule/' + ruleCode + '/versions', { headers: {'X-Requested-With':'XMLHttpRequest'} })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (!data.success) { showToast(data.error || 'خطأ', 'error'); overlay.remove(); return; }
        var body = overlay.querySelector('.version-modal-body');
        var today = new Date().toISOString().slice(0, 10);
        var html = '<div class="version-timeline">';

        if (data.versions.length === 0) {
            html += '<div style="text-align:center;color:#9CA3AF;padding:12px;">لا توجد نسخ تاريخية</div>';
        } else {
            data.versions.forEach(function(v) {
                var isCurrent = v.effective_from <= today && (v.effective_to === null || v.effective_to >= today);
                html += '<div class="version-item ' + (isCurrent ? 'current' : '') + '">' +
                    '<div class="version-dot"></div>' +
                    '<div class="version-info">' +
                        '<div class="version-dates">' +
                            'من ' + v.effective_from + (v.effective_to ? ' إلى ' + v.effective_to : ' (ساري)') +
                            (isCurrent ? ' <span class="version-badge">الحالي</span>' : '') +
                        '</div>' +
                        '<div class="version-value">' + v.current_value_json + '</div>' +
                    '</div>' +
                '</div>';
            });
        }
        html += '</div>';

        html += '<div class="version-add-form">' +
            '<h4>إضافة نسخة تاريخية</h4>' +
            '<div class="version-form-grid">' +
                '<div class="form-group"><label>من تاريخ</label><input type="date" id="ver-from"></div>' +
                '<div class="form-group"><label>إلى تاريخ</label><input type="date" id="ver-to"></div>' +
                '<div class="form-group" style="grid-column:1/-1;"><label>القيمة (JSON)</label><textarea id="ver-value" dir="ltr" placeholder=\'{"amount":"500.00"}\'></textarea></div>' +
                '<div class="form-group" style="grid-column:1/-1;"><label>السبب</label><input type="text" id="ver-reason" placeholder="إضافة قيمة تاريخية لاستيراد بيانات قديمة"></div>' +
            '</div>' +
            '<button class="btn-add-version" onclick="submitVersion(\'' + ruleCode + '\')">إضافة نسخة</button>' +
        '</div>';

        body.innerHTML = html;
    })
    .catch(function() { showToast('فشل تحميل النسخ', 'error'); overlay.remove(); });
}

function submitVersion(ruleCode) {
    var from = document.getElementById('ver-from').value;
    var to = document.getElementById('ver-to').value;
    var value = document.getElementById('ver-value').value;
    var reason = document.getElementById('ver-reason').value;

    if (!from || !to || !value) { showToast('يرجى ملء جميع الحقول', 'error'); return; }

    var formData = new FormData();
    formData.append('effective_from', from);
    formData.append('effective_to', to);
    formData.append('value_json', value);
    formData.append('change_reason', reason || 'إضافة نسخة تاريخية');
    formData.append('_token', document.querySelector('input[name="_token"]').value);

    fetch('/pricing/rule/' + ruleCode + '/add-version', {
        method: 'POST', body: formData, headers: {'X-Requested-With':'XMLHttpRequest'}
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            showToast('تم إضافة النسخة بنجاح', 'success');
            document.querySelector('.version-modal-overlay').remove();
        } else {
            showToast(data.error || 'حدث خطأ', 'error');
        }
    })
    .catch(function() { showToast('فشل الاتصال', 'error'); });
}
</script>
<?php $__template->endSection(); ?>
