@extends('layouts.fans')

@section('content')
    <div class="container mx-auto p-4">
        <h1 class="text-3xl font-extrabold text-center mb-6 text-gray-800">Purchase Your Ticket</h1>

        @if(session('error'))
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                {{ session('error') }}
            </div>
        @endif

        @if($errors->any())
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <ul>
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="bg-white p-6 rounded-xl shadow-lg max-w-lg mx-auto" x-data="ticketForm()" x-init="updateAmounts()">
            <form action="{{ route('fans.tickets.store') }}" method="POST">
                @csrf

                <div class="mb-4">
                    <label for="match_id" class="block text-gray-700 font-medium mb-2">Select Match</label>
                    <select name="match_id" id="match_id" x-model="matchId" @change="updateAmounts()" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150" required>
                        <option value="">Select a Match</option>
                        @foreach ($matches as $match)
                            <option value="{{ $match->match_id }}" 
                                data-vvip-amount="{{ $match->vvip_amount }}" 
                                data-vip-amount="{{ $match->vip_amount }}" 
                                data-1st-class-amount="{{ $match->{'1st_class_amount'} }}" 
                                data-seats='{{ json_encode($match->seats) }}'>
                                {{ $match->home_team }} vs {{ $match->away_team }} - {{ \Carbon\Carbon::parse($match->match_date)->format('Y-m-d H:i') }}
                            </option>
                        @endforeach
                    </select>
                    @error('match_id')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="mb-4">
                    <label for="seat_id" class="block text-gray-700 font-medium mb-2">Select Block</label>
                    <select name="seat_id" id="seat_id" x-model="seatId" @change="updateDetails()" class="w-full p-3 border border-gray-300 rounded-lg" required>
                        <option value="">Select a Block</option>
                        <!-- Options will be populated via JS based on matchId -->
                    </select>
                    @error('seat_id')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="mb-4">
                    <label for="category" class="block text-gray-700 font-medium mb-2">Ticket Category</label>
                    <select name="category" id="category" x-model="category" @change="updateAmounts()" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150" required>
                        <option value="vvip">VVIP</option>
                        <option value="vip">VIP</option>
                        <option value="1st_class">1st Class</option>
                    </select>
                    @error('category')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="mb-4">
                    <label for="amount_display" class="block text-gray-700 font-medium mb-2">Ticket Amount</label>
                    <input type="text" id="amount_display" x-model="amount" readonly class="w-full p-3 border border-gray-300 rounded-lg bg-gray-100" required>
                    <input type="hidden" name="amount" x-model="amount">
                    @error('amount')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <!-- NEW: Payment Method Selection -->
                <div class="mb-6">
                    <label for="payment_method" class="block text-gray-700 font-medium mb-2">Payment Method</label>
                    <select name="payment_method" id="payment_method" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150" required>
                        <option value="stripe">Credit/Debit Card (Stripe)</option>
                        <option value="paypal">PayPal</option>
                    </select>
                    @error('payment_method')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <button type="submit" class="w-full bg-indigo-600 text-white p-3 rounded-lg font-semibold hover:bg-indigo-700 transition duration-200 shadow-md">
                    Proceed to Payment
                </button>
            </form>
        </div>

        @if (session('ticket'))
            <div class="mt-8 max-w-2xl mx-auto bg-gradient-to-r from-green-600 via-green-700 to-emerald-800 rounded-xl shadow-2xl overflow-hidden relative border-4 border-yellow-400">
                <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22%3E%3Crect width=%22100%22 height=%22100%22 fill=%22%23ffffff%22 opacity=%220.2%22/%3E%3C/svg%3E')]"></div>
                <div class="relative p-4 text-white">
                    <div class="text-center border-b pb-4 mb-4 border-yellow-300">
                        <h2 class="text-xl font-bold uppercase tracking-widest">{{ session('ticket')->match->tournament_name }}</h2>
                    </div>
                    
                    <div class="flex justify-between items-center mb-4">
                        <img src="{{ asset('storage/'.$match->home_team_flag) }}" alt="Home Flag" class="h-6 w-6 rounded-full object-cover border" />
                        <h1 class="text-3xl font-extrabold text-yellow-300 uppercase">{{ session('ticket')->match->category }}</h1>
                        <img src="{{ asset('storage/'.$match->away_team_flag) }}" alt="Away Flag" class="h-6 w-6 rounded-full object-cover border" />
                    </div>

                    <div class="text-center mb-4 bg-yellow-400 text-green-800 p-2 rounded">
                        <h3 class="text-lg font-semibold">{{ session('ticket')->match->home_team }} <span class="text-green-800 font-bold">VS</span> {{ session('ticket')->match->away_team }}</h3>
                    </div>

                    <div class="bg-red-600 text-white p-2 text-center mb-4 rounded">
                        <p class="text-sm uppercase">Date: {{ \Carbon\Carbon::parse(session('ticket')->match->match_date)->format('d M Y') }} | Kick-Off: 3PM | Venue: {{ session('ticket')->match->venue }}</p>
                    </div>

                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div>
                            <p class="font-medium">Block: {{ session('ticket')->seat->block }}</p>
                        </div>
                        <div>
                            <p class="font-medium">Gate: {{ session('ticket')->seat->access_gate }}</p>
                        </div>
                        <div>
                            <p class="font-medium">Seat: {{ session('ticket')->seat->seat_number }}</p>
                        </div>
                        <div>
                            <p class="font-medium">Ticket No: {{ session('ticket')->ticket_number }}</p>
                        </div>
                        <div class="col-span-2">
                            <p class="font-medium">Price: SSP {{ number_format(session('ticket')->amount, 2) }}</p>
                        </div>
                    </div>

                    <div class="mt-4 text-center">
                        <p class="text-xs uppercase">Scan for Validation</p>
                        <div class="p-2 border border-yellow-300 rounded-lg bg-white">
                            {!! session('ticket')->qr_code !!}
                        </div>
                    </div>

                    <div class="mt-2 text-center">
                        <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/cf/FIFA_World_Cup_trophy.jpg/220px-FIFA_World_Cup_trophy.jpg" alt="FIFA Logo" class="w-16 mx-auto">
                    </div>
                </div>
            </div>
        @endif
    </div>

    <script>
        function ticketForm() {
            console.log('ticketForm initialized');
            return {
                matchId: '',
                seatId: '',
                category: 'vvip',
                vvipAmount: 0,
                vipAmount: 0,
                firstClassAmount: 0,
                amount: '',
                availableBlocks: [],

                updateAmounts() {
                    const select = document.getElementById('match_id');
                    const selectedOption = select.options[select.selectedIndex];
                    
                    if (selectedOption && this.matchId) {
                        this.vvipAmount = parseFloat(selectedOption.getAttribute('data-vvip-amount')) || 0;
                        this.vipAmount = parseFloat(selectedOption.getAttribute('data-vip-amount')) || 0;
                        this.firstClassAmount = parseFloat(selectedOption.getAttribute('data-1st-class-amount')) || 0;
                    } else {
                        this.vvipAmount = 0;
                        this.vipAmount = 0;
                        this.firstClassAmount = 0;
                    }

                    if (this.category === 'vvip') {
                        this.amount = this.vvipAmount.toFixed(2);
                    } else if (this.category === 'vip') {
                        this.amount = this.vipAmount.toFixed(2);
                    } else if (this.category === '1st_class') {
                        this.amount = this.firstClassAmount.toFixed(2);
                    } else {
                        this.amount = '';
                    }
                    this.loadBlocks();
                },
                
                loadBlocks() {
                    if (!this.matchId) {
                        this.availableBlocks = [];
                        return;
                    }
                    const select = document.getElementById('match_id');
                    const selectedOption = select.options[select.selectedIndex];
                    this.availableBlocks = JSON.parse(selectedOption.getAttribute('data-seats') || '[]');
                    
                    let seatSelect = document.getElementById('seat_id');
                    seatSelect.innerHTML = '<option value="">Select a Block</option>';
                    this.availableBlocks.forEach(block => {
                        let option = document.createElement('option');
                        option.value = block.id;
                        option.text = `${block.block} (${block.type}, ${block.access_gate})`;
                        seatSelect.appendChild(option);
                    });
                    seatSelect.value = this.seatId;
                },
                
                updateDetails() {
                    const block = this.availableBlocks.find(b => b.id == this.seatId);
                    if (block) {
                        this.category = block.type.toLowerCase().replace(/ /g, '_');
                        this.updateAmounts();
                    }
                },
            }
        }
    </script>
@endsection