@extends('layouts.admin')

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

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

                <input type="hidden" name="user_id" value="{{ Auth::id() }}">

                <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>

                <div class="mb-4">
                    <label for="purchase_channel" class="block text-gray-700 font-medium mb-2">Purchase Channel</label>
                    <select name="purchase_channel" id="purchase_channel" 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="ticket_center" selected>Ticket Center (Staff Issued)</option>
                        <option value="online">Online (User Purchase)</option>
                    </select>
                    @error('purchase_channel')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="mb-6">
                    <label for="status" class="block text-gray-700 font-medium mb-2">Status</label>
                    <select name="status" id="status" 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="valid">Valid (Default)</option>
                        <option value="used">Used</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                    @error('status')
                        <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">
                    Create Ticket
                </button>
            </form>
        </div>

        @if (session('ticket'))
            <div class="mt-8 max-w-md mx-auto bg-white rounded-xl shadow-2xl overflow-hidden relative border-4 border-indigo-600">
                <div class="absolute inset-0 bg-gray-50 bg-opacity-70"></div>
                <div class="relative p-8">
                    <div class="text-center border-b pb-4 mb-4">
                        <i class="fas fa-check-circle text-4xl text-green-500 mb-2"></i>
                        <h2 class="text-2xl font-bold text-gray-900">Ticket Successfully Issued!</h2>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-y-4 mb-6 text-sm">
                        <div class="col-span-2">
                            <p class="text-gray-600">Match:</p>
                            <p class="font-bold text-lg text-gray-800">{{ session('ticket')->match->home_team }} <span class="text-indigo-600">vs</span> {{ session('ticket')->match->away_team }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Date & Time:</p>
                            <p class="font-semibold">{{ \Carbon\Carbon::parse(session('ticket')->match->match_date)->format('M d, Y H:i') }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Ticket No:</p>
                            <p class="font-semibold text-indigo-700">{{ session('ticket')->ticket_number }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Category:</p>
                            <p class="font-semibold uppercase">{{ session('ticket')->category }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Block:</p>
                            <p class="font-semibold">{{ session('ticket')->seat->block }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Type of Seat:</p>
                            <p class="font-semibold">{{ session('ticket')->seat->type }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Access Gate:</p>
                            <p class="font-semibold">{{ session('ticket')->seat->access_gate }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Channel:</p>
                            <p class="font-semibold uppercase">{{ session('ticket')->purchase_channel }}</p>
                        </div>
                        <div>
                            <p class="text-gray-600">Status:</p>
                            <span class="px-2 py-1 text-xs font-semibold rounded-full @if(session('ticket')->status == 'valid') bg-green-100 text-green-800 @else bg-gray-100 text-gray-800 @endif">{{ session('ticket')->status }}</span>
                        </div>
                    </div>
                    
                    <div class="flex flex-col items-center">
                        <p class="text-xs text-gray-500 mb-2">Scan for Validation</p>
                        <div class="p-2 border border-gray-300 rounded-lg bg-white">
                            {!! session('ticket')->qr_code !!}
                        </div>
                    </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];
                    
                    // 1. Update Category Amounts (runs when matchId changes)
                    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 {
                        // Reset if no match is selected
                        this.vvipAmount = 0;
                        this.vipAmount = 0;
                        this.firstClassAmount = 0;
                    }

                    // 2. Update the main 'amount' property based on the selected category
                    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 = ''; // Fallback
                    }
                    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') || '[]');
                    
                    // Populate seat select options
                    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);
                    });
                },
                updateDetails() {
                    const block = this.availableBlocks.find(b => b.id == this.seatId);
                    if (block) {
                        this.category = block.type.toLowerCase().replace(/ /g, '_');
                        this.updateAmounts(); // Update amount after changing category
                    }
                },
            }
        }
    </script>
@endsection