<?php

namespace App\Http\Controllers;

use App\Models\MatchModel;
use App\Models\Ticket;
use App\Models\User;
use App\Traits\AuditLogTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class TicketController extends Controller
{
    use AuditLogTrait;
    
    public function create()
    {
        $matches = MatchModel::all();
        return view('tickets.create-ticket', compact('matches'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'match_id' => 'required|exists:matches,match_id',
            'category' => 'required|in:ordinary,vip',
            'purchase_channel' => 'required|in:online,ticket_center',
            'status' => 'required|in:valid,used,cancelled',
            'amount' => 'required|numeric|min:0',
        ]);

        // Use a transaction to prevent race conditions
        return DB::transaction(function () use ($validated) {
            // Fetch the match
            $match = MatchModel::findOrFail($validated['match_id']);

            // Count existing tickets for this match
            $soldTickets = Ticket::where('match_id', $validated['match_id'])->count();

            // Check if adding a new ticket would exceed the limit
            if ($soldTickets >= $match->total_ticket_number) {
                throw ValidationException::withMessages([
                    'match_id' => 'No more tickets available for this match.',
                ]);
            }

            $ticketNumber = 'TICKET-' . Str::random(8);

            // Use SVG format instead of PNG (doesn't require imagick)
            $qrCodeSvg = QrCode::size(300)->generate(url('/tickets/verify/' . $ticketNumber));

            $ticket = Ticket::create([
                'match_id' => $validated['match_id'],
                'category' => $validated['category'],
                'user_id' => auth()->id() ?? 1,
                'ticket_number' => $ticketNumber,
                'qr_code' => $qrCodeSvg,
                'purchase_channel' => $validated['purchase_channel'],
                'status' => $validated['status'],
            ]);

            // Save transaction
            $transaction = \App\Models\TransactionModel::create([
                'ticket_id' => $ticket->ticket_id,
                'user_id' => $ticket->user_id,
                'amount' => $validated['amount'],
                'payment_method' => 'cash', // Default, or set from request if needed
            ]);

            // Save revenue shares for this transaction
            \App\Models\Revenue::createFromTransaction($transaction->txn_id, $validated['amount']);

            $ticket->load('match');

            $this->logCreate($ticket, "Created new ticket: {$ticket->ticket_number} by user: " . auth()->user()->name);

            return redirect()->route('tickets.create')->with('ticket', $ticket);
        });
    }
}