<?php
use App\Modules\ActivitySubscriptions\Models\ActivityPricing;
$__template->layout('Layout.main');
?>
<?php $__template->section('title'); ?>تسعير الأنشطة<?php $__template->endSection(); ?>

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

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

<?php
// Build a helper to resolve reference_id → name
$refName = function(string $type, int $refId) use ($academyNames, $disciplineNames): string {
    if ($type === 'academy') {
        return $academyNames[$refId] ?? "أكاديمية #{$refId}";
    }
    if ($type === 'discipline') {
        return $disciplineNames[$refId] ?? "نشاط #{$refId}";
    }
    return "#{$refId}";
};

// Find which academies/disciplines already have pricing
$existingRefs = [];
foreach (($pricings ?? []) as $p) {
    $existingRefs[($p['pricing_type'] ?? '') . '_' . (int) ($p['reference_id'] ?? 0)] = true;
}
?>

<!-- Explanation Card -->
<div class="card" style="margin-bottom:20px;padding:20px;border-right:4px solid #0D7377;">
    <div style="display:flex;align-items:start;gap:12px;">
        <i data-lucide="info" style="width:20px;height:20px;color:#0D7377;flex-shrink:0;margin-top:2px;"></i>
        <div style="font-size:13px;color:#374151;line-height:1.8;">
            <strong>كيف يعمل التسعير:</strong>
            السعر الشهري يتحدد بناء على ثلاث عوامل: النشاط الرياضي، نوع الخدمة (حجم المجموعة)، ونوع العضوية (عضو / غير عضو).<br>
            كل ما قل حجم المجموعة زاد السعر (فردي اغلى من مجموعة). السعر ثابت لكل combination ولا يتغير حسب الاكاديمية او المدرب.<br>
            <span style="color:#6B7280;">
                <i data-lucide="arrow-left" style="width:12px;height:12px;vertical-align:middle;"></i>
                فردي (1 لاعب)
                <i data-lucide="arrow-left" style="width:12px;height:12px;vertical-align:middle;"></i>
                مجموعة صغيرة (2-4)
                <i data-lucide="arrow-left" style="width:12px;height:12px;vertical-align:middle;"></i>
                مجموعة (5-12)
                <i data-lucide="arrow-left" style="width:12px;height:12px;vertical-align:middle;"></i>
                فريق (13+)
            </span>
        </div>
    </div>
</div>

<!-- Filter Bar -->
<div class="card" style="margin-bottom:20px;padding:15px;">
    <form method="GET" action="/activity-subscriptions/pricing" style="display:flex;flex-wrap:wrap;gap:10px;align-items:end;">
        <div style="min-width:180px;">
            <label class="form-label" style="font-size:12px;">نوع التسعير</label>
            <select name="pricing_type" class="form-input">
                <option value="">الكل</option>
                <?php foreach ($pricingTypes as $ptKey => $ptLabel): ?>
                <option value="<?= e($ptKey) ?>" <?= ($filters['pricing_type'] ?? '') === $ptKey ? 'selected' : '' ?>><?= e($ptLabel) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="min-width:160px;">
            <label class="form-label" style="font-size:12px;">الحالة</label>
            <select name="is_active" class="form-input">
                <option value="" <?= ($filters['is_active'] ?? '') === '' ? 'selected' : '' ?>>الكل</option>
                <option value="1" <?= ($filters['is_active'] ?? '') === '1' ? 'selected' : '' ?>>فعّال</option>
                <option value="0" <?= ($filters['is_active'] ?? '') === '0' ? 'selected' : '' ?>>غير فعّال</option>
            </select>
        </div>
        <button type="submit" class="btn btn-outline"><i data-lucide="search" style="width:16px;height:16px;vertical-align:middle;"></i> بحث</button>
        <a href="/activity-subscriptions/pricing" class="btn btn-sm btn-outline" style="color:#6B7280;">مسح</a>
    </form>
</div>

<!-- Add New Pricing -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
        <i data-lucide="plus-circle" style="width:18px;height:18px;color:#0D7377;"></i>
        <h3 style="margin:0;color:#0D7377;font-size:15px;">إضافة تسعير جديد</h3>
    </div>
    <div style="padding:20px;">
        <form method="POST" action="/activity-subscriptions/pricing" style="display:flex;flex-wrap:wrap;gap:12px;align-items:end;">
            <?= csrf_field() ?>
            <div style="min-width:160px;">
                <label class="form-label" style="font-size:11px;">النوع</label>
                <select name="pricing_type" class="form-input" id="new-pricing-type" onchange="updateReferenceOptions()" required>
                    <option value="">-- اختر --</option>
                    <option value="academy">أكاديمية</option>
                    <option value="discipline">نشاط</option>
                </select>
            </div>
            <div style="min-width:200px;">
                <label class="form-label" style="font-size:11px;">الأكاديمية / النشاط</label>
                <select name="reference_id" class="form-input" id="new-reference-id" required>
                    <option value="">-- اختر النوع أولاً --</option>
                </select>
            </div>
            <div style="flex:1;min-width:110px;">
                <label class="form-label" style="font-size:11px;">سعر العضو</label>
                <input type="number" step="0.01" min="0" name="member_rate" value="0" class="form-input" style="font-size:13px;" required>
            </div>
            <div style="flex:1;min-width:110px;">
                <label class="form-label" style="font-size:11px;">سعر غير العضو</label>
                <input type="number" step="0.01" min="0" name="nonmember_rate" value="0" class="form-input" style="font-size:13px;" required>
            </div>
            <div style="flex:1;min-width:110px;">
                <label class="form-label" style="font-size:11px;">عضو (مسائي)</label>
                <input type="number" step="0.01" min="0" name="member_rate_pm" value="0" class="form-input" style="font-size:13px;">
            </div>
            <div style="flex:1;min-width:110px;">
                <label class="form-label" style="font-size:11px;">غير عضو (مسائي)</label>
                <input type="number" step="0.01" min="0" name="nonmember_rate_pm" value="0" class="form-input" style="font-size:13px;">
            </div>
            <div style="min-width:130px;">
                <label class="form-label" style="font-size:11px;">سريان من</label>
                <input type="date" name="effective_from" value="<?= e(date('Y-m-d')) ?>" class="form-input" style="font-size:13px;">
            </div>
            <button type="submit" class="btn btn-primary" style="font-size:13px;height:38px;">
                <i data-lucide="plus" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> إضافة
            </button>
        </form>
    </div>
</div>

<!-- Pricing Table -->
<?php if (!empty($pricings)): ?>
<div class="card" style="padding:0;overflow-x:auto;">
    <table style="width:100%;border-collapse:collapse;font-size:14px;" id="pricing-table">
        <thead>
            <tr style="background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">النوع</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">الأكاديمية / النشاط</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">سعر العضو</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">سعر غير العضو</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">عضو (مسائي)</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">غير عضو (مسائي)</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">سريان من</th>
                <th style="padding:12px 16px;text-align:right;font-weight:600;color:#374151;">سريان إلى</th>
                <th style="padding:12px 16px;text-align:center;font-weight:600;color:#374151;">الحالة</th>
                <th style="padding:12px 16px;text-align:center;font-weight:600;color:#374151;">إجراءات</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($pricings as $idx => $p):
                $typeLabel = ActivityPricing::getPricingTypeLabel($p['pricing_type'] ?? '');
                $isActive = (int) ($p['is_active'] ?? 0);
                $name = $refName($p['pricing_type'] ?? '', (int) ($p['reference_id'] ?? 0));
            ?>
            <tr style="border-bottom:1px solid #F3F4F6;" id="row-<?= $idx ?>">
                <td style="padding:12px 16px;">
                    <span style="background:#0D737715;color:#0D7377;font-size:12px;padding:4px 12px;border-radius:10px;font-weight:600;">
                        <?= e($typeLabel) ?>
                    </span>
                </td>
                <td style="padding:12px 16px;font-weight:600;"><?= e($name) ?></td>
                <td style="padding:12px 16px;"><?= money($p['member_rate'] ?? 0) ?></td>
                <td style="padding:12px 16px;"><?= money($p['nonmember_rate'] ?? 0) ?></td>
                <td style="padding:12px 16px;"><?= money($p['member_rate_pm'] ?? 0) ?></td>
                <td style="padding:12px 16px;"><?= money($p['nonmember_rate_pm'] ?? 0) ?></td>
                <td style="padding:12px 16px;font-size:13px;"><?= e($p['effective_from'] ?? '—') ?></td>
                <td style="padding:12px 16px;font-size:13px;"><?= e($p['effective_to'] ?? '—') ?></td>
                <td style="padding:12px 16px;text-align:center;">
                    <?php if ($isActive): ?>
                    <span class="badge" style="background:#05966915;color:#059669;font-size:12px;padding:4px 12px;border-radius:10px;font-weight:600;">فعّال</span>
                    <?php else: ?>
                    <span class="badge" style="background:#6B728015;color:#6B7280;font-size:12px;padding:4px 12px;border-radius:10px;font-weight:600;">غير فعّال</span>
                    <?php endif; ?>
                </td>
                <td style="padding:12px 16px;text-align:center;">
                    <button type="button" class="btn btn-sm btn-outline" style="font-size:12px;padding:4px 10px;" onclick="toggleEditRow(<?= $idx ?>)">
                        <i data-lucide="edit-3" style="width:13px;height:13px;vertical-align:middle;"></i> تعديل
                    </button>
                </td>
            </tr>
            <!-- Inline Edit Row -->
            <tr id="edit-row-<?= $idx ?>" style="display:none;background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                <td colspan="10" style="padding:20px;">
                    <form method="POST" action="/activity-subscriptions/pricing" style="display:flex;flex-wrap:wrap;gap:12px;align-items:end;">
                        <?= csrf_field() ?>
                        <input type="hidden" name="pricing_type" value="<?= e($p['pricing_type'] ?? '') ?>">
                        <input type="hidden" name="reference_id" value="<?= (int) ($p['reference_id'] ?? 0) ?>">
                        <div style="flex:1;min-width:120px;">
                            <label class="form-label" style="font-size:11px;">سعر العضو</label>
                            <input type="number" step="0.01" min="0" name="member_rate" value="<?= e($p['member_rate'] ?? '0') ?>" class="form-input" style="font-size:13px;">
                        </div>
                        <div style="flex:1;min-width:120px;">
                            <label class="form-label" style="font-size:11px;">سعر غير العضو</label>
                            <input type="number" step="0.01" min="0" name="nonmember_rate" value="<?= e($p['nonmember_rate'] ?? '0') ?>" class="form-input" style="font-size:13px;">
                        </div>
                        <div style="flex:1;min-width:120px;">
                            <label class="form-label" style="font-size:11px;">عضو (مسائي)</label>
                            <input type="number" step="0.01" min="0" name="member_rate_pm" value="<?= e($p['member_rate_pm'] ?? '0') ?>" class="form-input" style="font-size:13px;">
                        </div>
                        <div style="flex:1;min-width:120px;">
                            <label class="form-label" style="font-size:11px;">غير عضو (مسائي)</label>
                            <input type="number" step="0.01" min="0" name="nonmember_rate_pm" value="<?= e($p['nonmember_rate_pm'] ?? '0') ?>" class="form-input" style="font-size:13px;">
                        </div>
                        <div style="flex:1;min-width:130px;">
                            <label class="form-label" style="font-size:11px;">سريان من</label>
                            <input type="date" name="effective_from" value="<?= e($p['effective_from'] ?? date('Y-m-d')) ?>" class="form-input" style="font-size:13px;">
                        </div>
                        <div style="flex:1;min-width:130px;">
                            <label class="form-label" style="font-size:11px;">سريان إلى</label>
                            <input type="date" name="effective_to" value="<?= e($p['effective_to'] ?? '') ?>" class="form-input" style="font-size:13px;" placeholder="مفتوح">
                        </div>
                        <div style="display:flex;gap:6px;">
                            <button type="submit" class="btn btn-sm btn-primary" style="font-size:12px;">
                                <i data-lucide="check" style="width:13px;height:13px;vertical-align:middle;margin-left:3px;"></i> حفظ
                            </button>
                            <button type="button" class="btn btn-sm btn-outline" style="font-size:12px;color:#6B7280;" onclick="toggleEditRow(<?= $idx ?>)">
                                إلغاء
                            </button>
                        </div>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php if (isset($pagination) && ($pagination['last_page'] ?? 1) > 1): ?>
<div style="padding:15px;">
    <?php $__template->include('Shared.Components.pagination', ['pagination' => $pagination]); ?>
</div>
<?php endif; ?>

<?php else: ?>
<div class="card" style="padding:60px 20px;text-align:center;">
    <div style="margin-bottom:15px;">
        <i data-lucide="settings" style="width:48px;height:48px;color:#D1D5DB;"></i>
    </div>
    <h3 style="color:#6B7280;margin:0 0 8px;">لا توجد سجلات تسعير</h3>
    <p style="color:#9CA3AF;font-size:14px;margin:0;">
        <?php if (!empty($filters['pricing_type']) || ($filters['is_active'] ?? '') !== ''): ?>
            لا توجد نتائج مطابقة. جرب تغيير معايير البحث.
        <?php else: ?>
            لم يتم إعداد تسعير بعد. استخدم النموذج أعلاه لإضافة أسعار.
        <?php endif; ?>
    </p>
</div>
<?php endif; ?>

<!-- Academies/Disciplines without pricing -->
<?php
$missingAcademies = [];
foreach ($academies as $a) {
    $aid = (int) ($a['id'] ?? $a->id ?? 0);
    if (!isset($existingRefs['academy_' . $aid])) {
        $missingAcademies[] = $a;
    }
}
$missingDisciplines = [];
foreach ($disciplines as $d) {
    $did = (int) ($d['id'] ?? $d->id ?? 0);
    if (!isset($existingRefs['discipline_' . $did])) {
        $missingDisciplines[] = $d;
    }
}
?>
<?php if (!empty($missingAcademies) || !empty($missingDisciplines)): ?>
<div class="card" style="margin-top:20px;border-right:4px solid #D97706;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
        <i data-lucide="alert-triangle" style="width:18px;height:18px;color:#D97706;"></i>
        <h3 style="margin:0;color:#D97706;font-size:15px;">بدون تسعير (<?= count($missingAcademies) + count($missingDisciplines) ?>)</h3>
    </div>
    <div style="padding:15px 20px;font-size:13px;color:#6B7280;">
        <p style="margin:0 0 10px;">الأكاديميات والأنشطة التالية ليس لها أسعار محددة. لن يتم توليد اشتراكات لها حتى يتم تحديد أسعارها.</p>
        <?php if (!empty($missingAcademies)): ?>
        <div style="margin-bottom:8px;">
            <strong>أكاديميات:</strong>
            <?php foreach ($missingAcademies as $ma): ?>
            <span style="display:inline-block;background:#FEF3C7;color:#92400E;font-size:12px;padding:3px 10px;border-radius:8px;margin:2px 2px;"><?= e($ma['name_ar'] ?? $ma->name_ar ?? '') ?></span>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <?php if (!empty($missingDisciplines)): ?>
        <div>
            <strong>أنشطة:</strong>
            <?php foreach ($missingDisciplines as $md): ?>
            <span style="display:inline-block;background:#FEF3C7;color:#92400E;font-size:12px;padding:3px 10px;border-radius:8px;margin:2px 2px;"><?= e($md['name_ar'] ?? $md->name_ar ?? '') ?></span>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

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

function toggleEditRow(idx) {
    var editRow = document.getElementById('edit-row-' + idx);
    if (!editRow) return;
    if (editRow.style.display === 'none' || editRow.style.display === '') {
        var allEditRows = document.querySelectorAll('[id^="edit-row-"]');
        for (var i = 0; i < allEditRows.length; i++) {
            allEditRows[i].style.display = 'none';
        }
        editRow.style.display = 'table-row';
    } else {
        editRow.style.display = 'none';
    }
}

// Dynamic reference dropdown for the "Add new" form
var academyOptions = [
    <?php foreach ($academies as $a): ?>
    {id: <?= (int) ($a['id'] ?? $a->id ?? 0) ?>, name: <?= json_encode($a['name_ar'] ?? $a->name_ar ?? '', JSON_UNESCAPED_UNICODE) ?>},
    <?php endforeach; ?>
];
var disciplineOptions = [
    <?php foreach ($disciplines as $d): ?>
    {id: <?= (int) ($d['id'] ?? $d->id ?? 0) ?>, name: <?= json_encode($d['name_ar'] ?? $d->name_ar ?? '', JSON_UNESCAPED_UNICODE) ?>},
    <?php endforeach; ?>
];

function updateReferenceOptions() {
    var typeSelect = document.getElementById('new-pricing-type');
    var refSelect = document.getElementById('new-reference-id');
    var type = typeSelect.value;

    refSelect.innerHTML = '<option value="">-- اختر --</option>';

    var options = type === 'academy' ? academyOptions : (type === 'discipline' ? disciplineOptions : []);
    for (var i = 0; i < options.length; i++) {
        var opt = document.createElement('option');
        opt.value = options[i].id;
        opt.textContent = options[i].name;
        refSelect.appendChild(opt);
    }
}
</script>
<?php $__template->endSection(); ?>
