@extends('layouts.vendor')

@section('title', 'Subscription Plans')
@section('header_title', 'Vendor Store Subscription & Upgrade')

@section('content')
    <!-- Active Plan Status -->
    <div class="card" style="background: linear-gradient(135deg, rgba(236, 72, 153, 0.15), rgba(30, 41, 59, 0.8)); border: 1px solid var(--primary); margin-bottom: 2rem;">
        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
            <div>
                <div class="badge" style="background: var(--primary); color: #fff; margin-bottom: 8px;">CURRENT PLAN</div>
                <h2>{{ $activeSubscription->package->name ?? 'Free / Trial Plan' }}</h2>
                <p style="color: var(--text-muted); margin-top: 4px;">
                    @if($activeSubscription)
                        Active from {{ $activeSubscription->start_date->format('d M, Y') }} — <strong>Expires on {{ $activeSubscription->expires_at->format('d M, Y') }}</strong>
                        ({{ (int) now()->diffInDays($activeSubscription->expires_at, false) }} days remaining)
                    @else
                        Your subscription has expired. Upgrade to keep your frames active in the mobile app!
                    @endif
                </p>
            </div>
            <div>
                <span class="badge {{ $activeSubscription ? 'badge-success' : 'badge-danger' }}" style="font-size: 0.9rem; padding: 6px 16px;">
                    {{ $activeSubscription ? 'Active Subscription' : 'Plan Expired' }}
                </span>
            </div>
        </div>
    </div>

    <!-- Available Packages -->
    <h3 style="margin-bottom: 1.2rem;"><i class="fa-solid fa-crown" style="color: var(--primary);"></i> Upgrade or Extend Your Store Plan</h3>
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1.5rem; margin-bottom: 2.5rem;">
        @foreach($packages as $pkg)
            <div class="card" style="display: flex; flex-direction: column; justify-content: space-between; position: relative;">
                <div>
                    <h3 style="font-size: 1.25rem;">{{ $pkg->name }}</h3>
                    <div style="font-size: 2.2rem; font-weight: 800; color: #fff; margin: 0.8rem 0;">
                        ₹{{ number_format($pkg->payable_charge, 0) }}
                        <span style="font-size: 0.9rem; color: var(--text-muted); font-weight: 400;">/ {{ $pkg->months }} Month{{ $pkg->months > 1 ? 's' : '' }}</span>
                    </div>
                    <p style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 1rem;">{{ $pkg->description }}</p>
                </div>
                <button onclick="initiatePayment({{ $pkg->id }}, {{ $pkg->payable_charge }}, '{{ $pkg->name }}')" class="btn btn-primary" style="justify-content: center; width: 100%;">
                    <i class="fa-solid fa-bolt"></i> Upgrade via Razorpay
                </button>
            </div>
        @endforeach
    </div>

    <!-- Transaction History -->
    <div class="card">
        <h3><i class="fa-solid fa-receipt"></i> Payment & Billing History</h3>
        <table>
            <thead>
                <tr>
                    <th>Txn ID</th>
                    <th>Package</th>
                    <th>Amount</th>
                    <th>Payment Method</th>
                    <th>Status</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
                @forelse($transactions as $txn)
                    <tr>
                        <td><code>{{ $txn->txn_id }}</code></td>
                        <td>{{ $txn->package->name ?? 'Custom Plan' }}</td>
                        <td style="color: #10B981; font-weight: 700;">₹{{ number_format($txn->amount, 2) }}</td>
                        <td>{{ strtoupper($txn->gateway) }}</td>
                        <td>
                            <span class="badge {{ $txn->status === 'success' ? 'badge-success' : 'badge-danger' }}">
                                {{ ucfirst($txn->status) }}
                            </span>
                        </td>
                        <td>{{ $txn->created_at->format('d M Y, h:i A') }}</td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">No billing history found.</td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </div>

    <!-- Razorpay Checkout JS Script -->
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <script>
        function initiatePayment(packageId, amount, packageName) {
            fetch('/api/v1/payments/create-order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer {{ Auth::user()->createToken("web-session")->plainTextToken }}'
                },
                body: JSON.stringify({ package_id: packageId })
            })
            .then(res => res.json())
            .then(data => {
                if (!data.success) {
                    alert('Could not initialize payment order: ' + (data.message || 'Error'));
                    return;
                }

                const options = {
                    key: data.data.key_id,
                    amount: data.data.amount,
                    currency: data.data.currency,
                    name: 'MyOpticals',
                    description: packageName,
                    order_id: data.data.order_id,
                    handler: function(response) {
                        fetch('/api/v1/payments/verify', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'Authorization': 'Bearer {{ Auth::user()->createToken("web-session")->plainTextToken }}'
                            },
                            body: JSON.stringify({
                                order_id: response.razorpay_order_id,
                                payment_id: response.razorpay_payment_id,
                                signature: response.razorpay_signature,
                                package_id: packageId
                            })
                        })
                        .then(r => r.json())
                        .then(ver => {
                            if (ver.success) {
                                alert('🎉 Subscription activated successfully!');
                                window.location.reload();
                            } else {
                                alert('Verification issue: ' + ver.message);
                            }
                        });
                    },
                    prefill: {
                        name: '{{ Auth::user()->name }}',
                        email: '{{ Auth::user()->email }}',
                        contact: '{{ Auth::user()->phone }}'
                    },
                    theme: { color: '#EC4899' }
                };

                const rzp = new Razorpay(options);
                rzp.open();
            })
            .catch(err => {
                console.error(err);
                alert('Payment error occurred.');
            });
        }
    </script>
@endsection
