@extends('layouts.business')

@section('title', 'My Subscription')

@section('content')
<div class="container-fluid py-4">
    <!-- Header Section -->
    <div class="row mb-5">
        <div class="col-md-8">
            <h1 class="h2 fw-bold mb-0">
                <i class="fas fa-credit-card me-2"></i>My Subscription
            </h1>
            <p class="text-muted">Manage your plan and view available options</p>
        </div>
    </div>

    <!-- Current Subscription Info (If Exists) -->
    @if($currentSubscription)
    <div class="row mb-5">
        <div class="col-lg-12">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-primary text-white py-4">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h4 class="mb-1">
                                <i class="fas fa-check-circle me-2"></i>{{ $currentSubscription->plan->name }}
                            </h4>
                            <p class="mb-0 opacity-85">
                                {{ ucfirst($currentSubscription->plan->tier ?? 'N/A') }} Plan -
                                <span class="badge bg-white text-primary">Active</span>
                            </p>
                        </div>
                        <div class="col-md-6 text-md-end">
                            <h3 class="mb-1">AED {{ number_format($currentSubscription->plan->price, 2) }}</h3>
                            <p class="mb-0 opacity-85">per month</p>
                        </div>
                    </div>
                </div>

                <div class="card-body p-4">
                    <!-- Subscription Timeline -->
                    <div class="row mb-4">
                        <div class="col-sm-6 col-lg-3 mb-3 mb-lg-0">
                            <div class="text-center">
                                <p class="text-muted small mb-1">Subscription Period</p>
                                <h6 class="fw-bold">{{ $currentSubscription->start_date->format('M d') }} - {{ $currentSubscription->end_date->format('M d, Y') }}</h6>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 mb-3 mb-lg-0">
                            <div class="text-center">
                                <p class="text-muted small mb-1">Days Remaining</p>
                                <h6 class="fw-bold text-{{ $currentSubscription->daysRemaining() <= 7 ? 'warning' : 'success' }}">
                                    {{ $currentSubscription->daysRemaining() }} days
                                </h6>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3 mb-3 mb-lg-0">
                            <div class="text-center">
                                <p class="text-muted small mb-1">Auto-Renewal</p>
                                <h6 class="fw-bold">
                                    @if($currentSubscription->auto_renew)
                                        <span class="badge bg-success">Enabled</span>
                                    @else
                                        <span class="badge bg-secondary">Disabled</span>
                                    @endif
                                </h6>
                            </div>
                        </div>
                        <div class="col-sm-6 col-lg-3">
                            <div class="text-center">
                                <p class="text-muted small mb-1">Next Billing</p>
                                <h6 class="fw-bold">{{ $currentSubscription->next_billing_date->format('M d, Y') }}</h6>
                            </div>
                        </div>
                    </div>

                    <hr>

                    <!-- Expiring Warning -->
                    @if($currentSubscription->isExpiringSoon())
                    <div class="alert alert-warning alert-dismissible fade show mb-4" role="alert">
                        <i class="fas fa-clock me-2"></i>
                        <strong>Expiring Soon!</strong> Your subscription expires in {{ $currentSubscription->daysRemaining() }} days.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    @endif

                    <!-- Action Buttons -->
                    <div class="d-flex flex-wrap gap-2">
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#upgradeModal">
                            <i class="fas fa-arrow-up me-2"></i> Upgrade Plan
                        </button>
                        <button class="btn btn-outline-secondary" onclick="toggleAutoRenew()">
                            <i class="fas fa-{{ $currentSubscription->auto_renew ? 'toggle-on' : 'toggle-off' }} me-2"></i>
                            {{ $currentSubscription->auto_renew ? 'Disable' : 'Enable' }} Auto-Renewal
                        </button>
                        <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#cancelModal">
                            <i class="fas fa-times me-2"></i> Cancel Subscription
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Usage Overview Section -->
    <div class="row mb-5">
        <div class="col-lg-12">
            <h4 class="fw-bold mb-4">
                <i class="fas fa-chart-pie me-2 text-info"></i>Resource Usage
            </h4>
        </div>

        @php
            $venues = $usage['venues'] ?? ['used' => 0, 'limit' => 1, 'unlimited' => false];
            $staff = $usage['staff'] ?? ['used' => 0, 'limit' => 1, 'unlimited' => false];
            $offers = $usage['offers'] ?? ['used' => 0, 'limit' => 5, 'unlimited' => false];
            $campaigns = $usage['campaigns_this_month'] ?? ['used' => 0, 'limit' => 1, 'unlimited' => false];
        @endphp

        <!-- Venues Card -->
        <div class="col-lg-6 col-xxl-3 mb-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h6 class="fw-bold mb-0">Venues</h6>
                        <span class="badge bg-primary">{{ $venues['used'] }}/{{ $venues['unlimited'] ? '∞' : $venues['limit'] }}</span>
                    </div>
                    <div class="progress" style="height: 6px;">
                        <div class="progress-bar bg-primary" style="width: {{ $venues['unlimited'] ? 100 : ($venues['limit'] > 0 ? ($venues['used'] / $venues['limit'] * 100) : 0) }}%"></div>
                    </div>
                    <p class="text-muted small mt-2 mb-0">
                        {{ $venues['used'] }} of {{ $venues['unlimited'] ? 'unlimited' : $venues['limit'] }} venues used
                    </p>
                </div>
            </div>
        </div>

        <!-- Staff Members Card -->
        <div class="col-lg-6 col-xxl-3 mb-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h6 class="fw-bold mb-0">Staff Members</h6>
                        <span class="badge bg-success">{{ $staff['used'] }}/{{ $staff['unlimited'] ? '∞' : $staff['limit'] }}</span>
                    </div>
                    <div class="progress" style="height: 6px;">
                        <div class="progress-bar bg-success" style="width: {{ $staff['unlimited'] ? 100 : ($staff['limit'] > 0 ? ($staff['used'] / $staff['limit'] * 100) : 0) }}%"></div>
                    </div>
                    <p class="text-muted small mt-2 mb-0">
                        {{ $staff['used'] }} of {{ $staff['unlimited'] ? 'unlimited' : $staff['limit'] }} staff members used
                    </p>
                </div>
            </div>
        </div>

        <!-- Offers Card -->
        <div class="col-lg-6 col-xxl-3 mb-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h6 class="fw-bold mb-0">Offers</h6>
                        <span class="badge bg-warning">{{ $offers['used'] }}/{{ $offers['unlimited'] ? '∞' : $offers['limit'] }}</span>
                    </div>
                    <div class="progress" style="height: 6px;">
                        <div class="progress-bar bg-warning" style="width: {{ $offers['unlimited'] ? 100 : ($offers['limit'] > 0 ? ($offers['used'] / $offers['limit'] * 100) : 0) }}%"></div>
                    </div>
                    <p class="text-muted small mt-2 mb-0">
                        {{ $offers['used'] }} of {{ $offers['unlimited'] ? 'unlimited' : $offers['limit'] }} offers used
                    </p>
                </div>
            </div>
        </div>

        <!-- Campaigns Card -->
        <div class="col-lg-6 col-xxl-3 mb-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <h6 class="fw-bold mb-0">Campaigns (Month)</h6>
                        <span class="badge bg-info">{{ $campaigns['used'] }}/{{ $campaigns['unlimited'] ? '∞' : $campaigns['limit'] }}</span>
                    </div>
                    <div class="progress" style="height: 6px;">
                        <div class="progress-bar bg-info" style="width: {{ $campaigns['unlimited'] ? 100 : ($campaigns['limit'] > 0 ? ($campaigns['used'] / $campaigns['limit'] * 100) : 0) }}%"></div>
                    </div>
                    <p class="text-muted small mt-2 mb-0">
                        {{ $campaigns['used'] }} of {{ $campaigns['unlimited'] ? 'unlimited' : $campaigns['limit'] }} campaigns used
                    </p>
                </div>
            </div>
        </div>
    </div>

    @else
    <!-- No Subscription State -->
    <div class="row mb-5">
        <div class="col-lg-12">
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="fas fa-info-circle me-2"></i>
                <strong>No Active Subscription:</strong> You don't have an active subscription. Choose a plan below to get started!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
    </div>
    @endif

    <!-- Plan Comparison Cards (Dynamic & Enhanced) - MERGED FROM PLANS PAGE -->
    <div class="row mb-5">
        <div class="col-lg-12 mb-4">
            <h4 class="fw-bold mb-2">
                <i class="fas fa-layer-group me-2 text-primary"></i>{{ $currentSubscription ? 'Other Available Plans' : 'Choose Your Plan' }}
            </h4>
            <p class="text-muted">{{ $currentSubscription ? 'Upgrade to access more features' : 'Scale your business with the right features at the right price' }}</p>
        </div>

        @forelse($availablePlans as $plan)
        <div class="col-lg-4 mb-4">
            <div class="card h-100 border-0 plan-card-enhanced {{ $plan->is_popular ? 'shadow-lg' : 'shadow-sm' }}"
                 style="transition: all 0.3s ease; {{ $plan->is_popular ? 'transform: translateY(-10px); border: 3px solid #28a745;' : '' }}">

                <!-- Ribbon -->
                @if($plan->is_popular)
                <div class="position-absolute top-0 end-0" style="z-index: 10;">
                    <span class="badge bg-success rounded-pill px-4 py-2" style="border-radius: 0 0 0 8px; font-size: 0.85rem;">
                        <i class="fas fa-star me-1"></i>MOST POPULAR
                    </span>
                </div>
                @endif

                <!-- Header with Gradient -->
                <div class="card-header border-0 py-5"
                     style="background: linear-gradient(135deg, {{ $plan->is_popular ? '#28a745' : '#007bff' }} 0%, {{ $plan->is_popular ? '#20c997' : '#0056b3' }} 100%);">
                    <h3 class="mb-1 fw-bold text-white">{{ $plan->name }}</h3>
                    <small class="text-white opacity-90">{{ $plan->description }}</small>
                </div>

                <!-- Body -->
                <div class="card-body p-4 d-flex flex-column">
                    <!-- Price Section -->
                    <div class="mb-4 pb-3 border-bottom">
                        <h2 class="mb-1">
                            <span class="fw-bold">AED {{ number_format($plan->price, 2) }}</span>
                        </h2>
                        <p class="text-muted small mb-0">per month, billed monthly</p>
                    </div>

                    <!-- Features List (Enhanced) -->
                    <ul class="list-unstyled mb-4 flex-grow-1">
                        @if($plan->max_venues)
                        <li class="mb-3 d-flex align-items-start">
                            <i class="fas fa-check-circle text-success me-3 mt-1" style="flex-shrink: 0;"></i>
                            <div>
                                <strong>{{ $plan->max_venues == -1 ? 'Unlimited' : $plan->max_venues }}</strong>
                                <span class="text-muted small">{{ $plan->max_venues == 1 ? 'Venue' : 'Venues' }}</span>
                            </div>
                        </li>
                        @endif

                        @if($plan->max_offers)
                        <li class="mb-3 d-flex align-items-start">
                            <i class="fas fa-check-circle text-success me-3 mt-1" style="flex-shrink: 0;"></i>
                            <div>
                                <strong>{{ $plan->max_offers == -1 ? 'Unlimited' : $plan->max_offers }}</strong>
                                <span class="text-muted small">{{ $plan->max_offers == 1 ? 'Offer' : 'Offers' }}</span>
                            </div>
                        </li>
                        @endif

                        @if($plan->max_staff)
                        <li class="mb-3 d-flex align-items-start">
                            <i class="fas fa-check-circle text-success me-3 mt-1" style="flex-shrink: 0;"></i>
                            <div>
                                <strong>{{ $plan->max_staff == -1 ? 'Unlimited' : $plan->max_staff }}</strong>
                                <span class="text-muted small">{{ $plan->max_staff == 1 ? 'Staff Member' : 'Staff Members' }}</span>
                            </div>
                        </li>
                        @endif


                        @if($plan->monthly_campaigns)
                        <li class="mb-3 d-flex align-items-start">
                            <i class="fas fa-check-circle text-success me-3 mt-1" style="flex-shrink: 0;"></i>
                            <div>
                                <strong>{{ $plan->monthly_campaigns == -1 ? 'Unlimited' : $plan->monthly_campaigns }}</strong>
                                <span class="text-muted small">Campaign(s) per Month</span>
                            </div>
                        </li>
                        @endif

                        @if($plan->analytics_access)
                        <li class="mb-3 d-flex align-items-start">
                            <i class="fas fa-check-circle text-success me-3 mt-1" style="flex-shrink: 0;"></i>
                            <span>Advanced Analytics</span>
                        </li>
                        @endif

                        @if($plan->priority_support)
                        <li class="mb-0 d-flex align-items-start">
                            <i class="fas fa-check-circle text-success me-3 mt-1" style="flex-shrink: 0;"></i>
                            <span>Priority Support (24/7)</span>
                        </li>
                        @endif
                    </ul>

                    <!-- Call-to-Action Button -->
                    @if($currentSubscription && $currentSubscription->plan->id === $plan->id)
                    <button class="btn btn-success w-100 disabled" style="font-weight: 600;">
                        <i class="fas fa-check me-2"></i>Current Plan
                    </button>
                    @else
                    <button class="btn {{ $plan->is_popular ? 'btn-success' : 'btn-primary' }} btn-lg w-100"
                            onclick="selectPlan({{ $plan->id }})"
                            style="font-weight: 600;">
                        <i class="fas fa-arrow-right me-2"></i>Choose {{ $plan->name }}
                    </button>
                    @endif
                </div>
            </div>
        </div>
        @empty
        <div class="col-12 text-center py-5">
            <i class="fas fa-inbox" style="font-size: 3rem; color: #ddd;"></i>
            <p class="text-muted mt-3">No subscription plans available</p>
        </div>
        @endforelse
    </div>

    <!-- Feature Comparison Table -->
    <div class="row mb-5">
        <div class="col-lg-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-light py-4">
                    <h5 class="mb-0 fw-bold">
                        <i class="fas fa-table me-2"></i>Plan Comparison
                    </h5>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="fw-bold">Feature</th>
                                @foreach($availablePlans as $plan)
                                <th class="text-center fw-bold">{{ $plan->name }}</th>
                                @endforeach
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="fw-bold">Venues</td>
                                @foreach($availablePlans as $plan)
                                <td class="text-center">
                                    {{ $plan->max_venues == -1 ? '∞' : $plan->max_venues }}
                                </td>
                                @endforeach
                            </tr>
                            <tr>
                                <td class="fw-bold">Offers</td>
                                @foreach($availablePlans as $plan)
                                <td class="text-center">
                                    {{ $plan->max_offers == -1 ? '∞' : $plan->max_offers }}
                                </td>
                                @endforeach
                            </tr>
                            <tr>
                                <td class="fw-bold">Staff Members</td>
                                @foreach($availablePlans as $plan)
                                <td class="text-center">
                                    {{ $plan->max_staff == -1 ? '∞' : $plan->max_staff }}
                                </td>
                                @endforeach
                            </tr>

                            <tr>
                                <td class="fw-bold">Campaigns/Month</td>
                                @foreach($availablePlans as $plan)
                                <td class="text-center">
                                    {{ $plan->monthly_campaigns == -1 ? '∞' : $plan->monthly_campaigns }}
                                </td>
                                @endforeach
                            </tr>
                            <tr>
                                <td class="fw-bold">Analytics</td>
                                @foreach($availablePlans as $plan)
                                <td class="text-center">
                                    @if($plan->analytics_access)
                                    <i class="fas fa-check text-success"></i>
                                    @else
                                    <i class="fas fa-times text-danger"></i>
                                    @endif
                                </td>
                                @endforeach
                            </tr>
                            <tr>
                                <td class="fw-bold">Priority Support</td>
                                @foreach($availablePlans as $plan)
                                <td class="text-center">
                                    @if($plan->priority_support)
                                    <i class="fas fa-check text-success"></i>
                                    @else
                                    <i class="fas fa-times text-danger"></i>
                                    @endif
                                </td>
                                @endforeach
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Upgrade Modal -->
<div class="modal fade" id="upgradeModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0">
            <div class="modal-header bg-light border-0">
                <h5 class="modal-title fw-bold">
                    <i class="fas fa-arrow-up me-2 text-success"></i>Upgrade Your Plan
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <p class="text-muted mb-4">Select a new plan to upgrade to:</p>
                <form id="upgradeForm">
                    @csrf
                    <select name="plan_id" class="form-select mb-3" required>
                        <option value="">Choose a plan...</option>
                        @foreach($availablePlans as $plan)
                        @if(!$currentSubscription || $plan->id !== $currentSubscription->plan->id)
                        <option value="{{ $plan->id }}">
                            {{ $plan->name }} - AED {{ number_format($plan->price, 2) }}/month
                        </option>
                        @endif
                        @endforeach
                    </select>
                    <button type="submit" class="btn btn-success w-100">
                        <i class="fas fa-check me-2"></i>Upgrade Now
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Cancel Modal -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0">
            <div class="modal-header bg-light border-0">
                <h5 class="modal-title fw-bold">
                    <i class="fas fa-exclamation-triangle me-2 text-danger"></i>Cancel Subscription
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                @if($currentSubscription)
                <div class="alert alert-warning mb-4">
                    <i class="fas fa-info-circle me-2"></i>
                    Your access will continue until <strong>{{ $currentSubscription->end_date->format('M d, Y') }}</strong>.
                </div>
                @endif
                <form id="cancelForm">
                    @csrf
                    <div class="mb-3">
                        <label class="form-label">Tell us why (optional)</label>
                        <textarea name="reason" class="form-control" rows="3" placeholder="Your feedback helps us improve..."></textarea>
                    </div>
                    <button type="submit" class="btn btn-danger w-100">
                        <i class="fas fa-times me-2"></i>Cancel Subscription
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
.plan-card-enhanced {
    border-radius: 12px;
    overflow: hidden;
    position: relative;
}

.plan-card-enhanced:hover {
    box-shadow: 0 1.5rem 3rem rgba(0, 0, 0, 0.2) !important;
    transform: translateY(-8px);
}

.plan-card-enhanced.shadow-lg {
    box-shadow: 0 1rem 3rem rgba(40, 167, 69, 0.3) !important;
}

.plan-card-enhanced.shadow-lg:hover {
    box-shadow: 0 1.5rem 4rem rgba(40, 167, 69, 0.4) !important;
    transform: translateY(-15px);
}
</style>

<script>
function selectPlan(planId) {
    // Use plan ID directly to redirect to upgrade page
    window.location.href = `/business/subscription/upgrade/${planId}`;
}

function toggleAutoRenew() {
    fetch('{{ route("business.subscription.index") }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            action: 'toggle_auto_renew'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    });
}

document.getElementById('upgradeForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const planId = this.querySelector('select[name="plan_id"]').value;
    if (planId) {
        window.location.href = `/business/subscription/upgrade/${planId}`;
    }
});

document.getElementById('cancelForm').addEventListener('submit', function(e) {
    e.preventDefault();
    if (confirm('Are you sure you want to cancel your subscription? Your access will continue until the end of your billing period.')) {
        fetch('{{ route("business.subscription.cancel") }}', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                reason: document.querySelector('textarea[name="reason"]').value
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Subscription cancelled successfully');
                location.reload();
            } else {
                alert('Error: ' + (data.message || 'Failed to cancel'));
            }
        });
    }
});
</script>
@endsection

