@extends('patient.layouts.app')
@section('title','اشتراكي')

@push('styles')
<style>
.plan-card {
    border-radius: 20px;
    padding: 1.4rem;
    margin-bottom: 1rem;
    position: relative;
    overflow: hidden;
    border: 2px solid transparent;
    transition: transform .2s, box-shadow .2s;
}
.plan-card:active { transform: scale(.98); }

.plan-card.free     { background: #fff;    border-color: #e5e7eb; }
.plan-card.basic    { background: #fff;    border-color: #bfdbfe; }
.plan-card.premium  { background: linear-gradient(145deg, #5b21b6, #7c3aed); color: #fff; border-color: transparent; box-shadow: 0 8px 30px rgba(124,58,237,.4); }
.plan-card.premium .plan-price { color: #fff; }
.plan-card.premium .plan-period { color: rgba(255,255,255,.7); }
.plan-card.premium .feature-item { color: rgba(255,255,255,.9); }
.plan-card.premium .feature-icon { color: #a78bfa; }

.plan-badge {
    position: absolute;
    top: 14px; left: 14px;
    background: #fbbf24;
    color: #78350f;
    font-size: .65rem;
    font-weight: 700;
    padding: 3px 10px;
    border-radius: 20px;
    text-transform: uppercase;
    letter-spacing: .06em;
}

.plan-name  { font-size: 1.1rem; font-weight: 700; margin-bottom: 2px; }
.plan-price { font-size: 2rem;   font-weight: 900; line-height: 1; color: #7c3aed; }
.plan-period{ font-size: .75rem; color: #94a3b8; margin-bottom: 1rem; }

.feature-item {
    display: flex; align-items: center; gap: 8px;
    font-size: .82rem; margin-bottom: 6px; color: #374151;
}
.feature-icon { font-size: .9rem; flex-shrink: 0; }

.btn-subscribe {
    width: 100%; padding: .75rem; border-radius: 12px;
    font-weight: 700; font-size: .95rem; cursor: pointer;
    border: none; margin-top: 1.1rem; transition: all .15s;
}
.btn-free    { background: #f3f4f6; color: #374151; }
.btn-basic   { background: #1d4ed8; color: #fff; }
.btn-premium { background: rgba(255,255,255,.2); color: #fff; border: 2px solid rgba(255,255,255,.5); backdrop-filter: blur(4px); }
.btn-premium:hover { background: rgba(255,255,255,.3); }
.btn-current { background: #d1fae5; color: #065f46; }
.btn-current-premium { background: rgba(255,255,255,.15); color: #fff; border: 2px solid rgba(255,255,255,.4); }

.current-banner {
    background: linear-gradient(135deg, #5b21b6, #7c3aed);
    border-radius: 20px;
    padding: 1.3rem;
    color: #fff;
    margin-bottom: 1.2rem;
    box-shadow: 0 6px 20px rgba(124,58,237,.3);
}
.progress-bar-sub {
    height: 6px;
    border-radius: 3px;
    background: rgba(255,255,255,.25);
    overflow: hidden;
    margin-top: .6rem;
}
.progress-fill {
    height: 100%;
    background: #a78bfa;
    border-radius: 3px;
    transition: width .5s;
}

.toggle-billing {
    display: flex; align-items: center; justify-content: center;
    gap: 10px; margin-bottom: 1.2rem;
}
.toggle-track {
    width: 48px; height: 26px;
    background: #e5e7eb; border-radius: 13px;
    position: relative; cursor: pointer;
    transition: background .2s;
}
.toggle-track.on { background: #7c3aed; }
.toggle-knob {
    width: 20px; height: 20px;
    background: #fff; border-radius: 50%;
    position: absolute; top: 3px; right: 3px;
    transition: transform .2s;
    box-shadow: 0 1px 4px rgba(0,0,0,.2);
}
.toggle-track.on .toggle-knob { transform: translateX(-22px); }
.save-badge {
    background: #d1fae5; color: #065f46;
    font-size: .68rem; font-weight: 700;
    padding: 2px 8px; border-radius: 20px;
}
</style>
@endpush

@section('content')

{{-- ══ الاشتراك الحالي ══ --}}
@if($currentSub)
<div class="current-banner">
    <div class="d-flex align-items-start justify-content-between mb-2">
        <div>
            <div style="font-size:.75rem;opacity:.75">اشتراكك الحالي</div>
            <div style="font-size:1.2rem;font-weight:700">{{ $currentSub->plan->name_ar }}</div>
        </div>
        <span style="background:rgba(255,255,255,.2);border-radius:20px;padding:4px 12px;font-size:.75rem;font-weight:600">
            نشط ✓
        </span>
    </div>
    <div style="font-size:.8rem;opacity:.8">
        ينتهي في {{ $currentSub->ends_at->format('Y/m/d') }}
        — {{ $currentSub->daysRemaining() }} يوم متبقي
    </div>
    @php
        $totalDays = $currentSub->starts_at->diffInDays($currentSub->ends_at);
        $usedDays  = $currentSub->starts_at->diffInDays(now());
        $pct       = $totalDays > 0 ? min(100, round(($usedDays / $totalDays) * 100)) : 0;
    @endphp
    <div class="progress-bar-sub">
        <div class="progress-fill" style="width:{{ $pct }}%"></div>
    </div>
    @if(!$currentSub->plan->isFree())
    <form method="POST" action="{{ route('patient.subscription.cancel') }}" class="mt-2">
        @csrf
        <button type="submit"
                style="background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.3);border-radius:8px;color:rgba(255,255,255,.8);padding:5px 14px;font-size:.78rem;cursor:pointer"
                onclick="return confirm('إلغاء الاشتراك؟ ستبقى المميزات حتى نهاية الفترة.')">
            إلغاء الاشتراك
        </button>
    </form>
    @endif
</div>
@endif

{{-- ══ تبديل شهري / سنوي ══ --}}
<div class="toggle-billing">
    <span style="font-size:.85rem;font-weight:600;color:#374151">شهري</span>
    <div class="toggle-track" id="billingToggle" onclick="toggleBilling()">
        <div class="toggle-knob"></div>
    </div>
    <span style="font-size:.85rem;font-weight:600;color:#374151">سنوي</span>
    <span class="save-badge" id="saveBadge" style="display:none">وفّر 17%</span>
</div>

{{-- ══ الباقات ══ --}}
@foreach($plans as $plan)
@php
    $type    = strtolower($plan->name);
    $isCurrent = $currentSub && $currentSub->plan_id === $plan->id;
@endphp

<div class="plan-card {{ $type }}">
    @if($type === 'premium')
        <div class="plan-badge">⭐ الأفضل</div>
    @endif
    @if($isCurrent)
        <div class="plan-badge" style="background:#d1fae5;color:#065f46">✓ اشتراكك</div>
    @endif

    <div class="d-flex align-items-start justify-content-between mb-3">
        <div>
            <div class="plan-name">{{ $plan->name_ar }}</div>
            <div style="font-size:.78rem;{{ $type==='premium' ? 'color:rgba(255,255,255,.7)' : 'color:#64748b' }}">
                {{ $plan->description }}
            </div>
        </div>
        <div class="text-end">
            @if($plan->isFree())
                <div class="plan-price">مجاناً</div>
            @else
                <div class="plan-price" id="price-{{ $plan->id }}">
                    ${{ number_format($plan->price_monthly, 2) }}
                </div>
                <div class="plan-period" id="period-{{ $plan->id }}">/شهر</div>
            @endif
        </div>
    </div>

    {{-- قائمة المميزات --}}
    <div>
        @if($plan->unlimited_appointments)
        <div class="feature-item">
            <span class="feature-icon">✅</span>
            <span>مواعيد غير محدودة</span>
        </div>
        @else
        <div class="feature-item">
            <span class="feature-icon">📅</span>
            <span>{{ $plan->appointments_per_month }} مواعيد شهرياً</span>
        </div>
        @endif

        @if($plan->priority_queue)
        <div class="feature-item">
            <span class="feature-icon">⚡</span>
            <span>أولوية في الطابور</span>
        </div>
        @endif

        @if($plan->medical_records_access)
        <div class="feature-item">
            <span class="feature-icon">📁</span>
            <span>سجلات طبية كاملة</span>
        </div>
        @endif

        @if($plan->prescription_download)
        <div class="feature-item">
            <span class="feature-icon">💊</span>
            <span>تحميل الوصفات الطبية</span>
        </div>
        @endif

        @if($plan->lab_results_upload)
        <div class="feature-item">
            <span class="feature-icon">🔬</span>
            <span>رفع نتائج التحاليل</span>
        </div>
        @endif

        @if($plan->online_consultation)
        <div class="feature-item">
            <span class="feature-icon">💬</span>
            <span>استشارة طبية أونلاين</span>
        </div>
        @endif

        @if($plan->family_members)
        <div class="feature-item">
            <span class="feature-icon">👨‍👩‍👧</span>
            <span>{{ $plan->family_members_count }} أفراد عائلة</span>
        </div>
        @endif

        @if(!$plan->show_ads)
        <div class="feature-item">
            <span class="feature-icon">🚫</span>
            <span>بدون إعلانات</span>
        </div>
        @endif
    </div>

    {{-- زر الاشتراك --}}
    @if($isCurrent)
        <button class="btn-subscribe {{ $type==='premium' ? 'btn-current-premium' : 'btn-current' }}" disabled>
            ✓ اشتراكك الحالي
        </button>
    @elseif($plan->isFree())
        <form method="GET" action="{{ route('patient.subscription.choose', $plan->id) }}">
            <button type="submit" class="btn-subscribe btn-free">
                التحويل للمجانية
            </button>
        </form>
    @else
        <a href="{{ route('patient.subscription.choose', $plan->id) }}"
           class="btn-subscribe {{ $type==='premium' ? 'btn-premium' : 'btn-basic' }}"
           style="display:block;text-align:center;text-decoration:none"
           id="sub-btn-{{ $plan->id }}">
            @if($type === 'premium') 🚀 @endif
            اشترك الآن
        </a>
    @endif
</div>
@endforeach

{{-- ══ سجل الاشتراكات ══ --}}
@if($history->isNotEmpty())
<div class="p-card mt-2">
    <div class="p-card-title">سجل الاشتراكات</div>
    @foreach($history as $h)
    <div class="d-flex align-items-center justify-content-between py-2 border-bottom" style="border-color:#f3f4f6!important">
        <div>
            <div class="fw-semibold small">{{ $h->plan->name_ar }}</div>
            <div style="font-size:.72rem;color:#94a3b8">
                {{ $h->starts_at->format('Y/m/d') }} ← {{ $h->ends_at->format('Y/m/d') }}
            </div>
        </div>
        <div class="text-end">
            @php $sc=['active'=>['#d1fae5','#065f46','نشط'],'expired'=>['#fee2e2','#991b1b','منتهي'],'cancelled'=>['#fef3c7','#92400e','ملغي'],'trial'=>['#eff6ff','#1e40af','تجريبي']]; [$bg,$cl,$lb]=$sc[$h->status]??['#e5e7eb','#374151','—']; @endphp
            <span class="badge" style="background:{{ $bg }};color:{{ $cl }}">{{ $lb }}</span>
            @if($h->amount_paid > 0)
            <div style="font-size:.72rem;color:#94a3b8">${{ $h->amount_paid }}</div>
            @endif
        </div>
    </div>
    @endforeach
</div>
@endif

{{-- ══ أسئلة شائعة ══ --}}
<div class="p-card mt-2">
    <div class="p-card-title">أسئلة شائعة</div>
    @foreach([
        ['هل يمكن إلغاء الاشتراك؟', 'نعم، يمكنك الإلغاء في أي وقت. ستبقى المميزات حتى نهاية فترة الاشتراك المدفوعة.'],
        ['كيف يتم الدفع؟', 'ندعم الدفع بالبطاقة الائتمانية، Tap، أو النقد عند نقاط الدفع المعتمدة.'],
        ['ما الفرق بين الشهري والسنوي؟', 'الاشتراك السنوي أوفر بنسبة 17% — تدفع مقابل 10 أشهر وتحصل على 12.'],
    ] as [$q,$a])
    <div class="mb-3">
        <div class="fw-semibold small">{{ $q }}</div>
        <div style="font-size:.8rem;color:#64748b;margin-top:2px">{{ $a }}</div>
    </div>
    @endforeach
</div>

@endsection

@push('scripts')
<script>
let isYearly = false;
const prices = @json($plans->mapWithKeys(fn($p) => [$p->id => ['monthly' => $p->price_monthly, 'yearly' => $p->price_yearly, 'free' => $p->isFree()]]));

function toggleBilling() {
    isYearly = !isYearly;
    const track = document.getElementById('billingToggle');
    track.classList.toggle('on', isYearly);
    document.getElementById('saveBadge').style.display = isYearly ? 'inline-block' : 'none';

    // تحديث الأسعار
    Object.entries(prices).forEach(([id, p]) => {
        if (p.free) return;
        const priceEl  = document.getElementById('price-' + id);
        const periodEl = document.getElementById('period-' + id);
        if (!priceEl) return;

        if (isYearly) {
            priceEl.textContent  = '$' + parseFloat(p.yearly).toFixed(2);
            periodEl.textContent = '/سنة';
        } else {
            priceEl.textContent  = '$' + parseFloat(p.monthly).toFixed(2);
            periodEl.textContent = '/شهر';
        }
    });
}
</script>
@endpush
