<?php

namespace App\Http\Controllers;

use App\Models\MatchModel;
use App\Models\Seat;
use App\Traits\AuditLogTrait;
use Illuminate\Http\Request;

class MatchController extends Controller
{
    use AuditLogTrait;
    public function index()
    {
        $matches = MatchModel::orderBy('match_date', 'desc')->get();
        return view('admin.matches.index', compact('matches'));
    }

    public function create()
    {
        return view('admin.matches.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'tournament_name' => 'required|string|max:100',
            'home_team' => 'required|string|max:100',
            'away_team' => 'required|string|max:100',
            'match_date' => 'required|date|after:now',
            'stadium' => 'required|string|max:100',
            'home_team_flag' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'away_team_flag' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'vvip_amount' => 'required|numeric|min:0',
            'vip_amount' => 'required|numeric|min:0',
            '1st_class_amount' => 'required|numeric|min:0',
            'blocks' => 'required|array', // Optional: ensure at least one block is selected
            'blocks.*' => 'exists:seats,id',
        ]);

        // Handle file uploads
        $homeFlagPath = $request->file('home_team_flag')->store('flags', 'public');
        $awayFlagPath = $request->file('away_team_flag')->store('flags', 'public');

        $match = MatchModel::create([
            'home_team' => $validated['home_team'],
            'away_team' => $validated['away_team'],
            'match_date' => $validated['match_date'],
            'stadium' => $validated['stadium'],
            'home_team_flag' => $homeFlagPath,
            'away_team_flag' => $awayFlagPath,
            'vvip_amount' => $validated['vvip_amount'],
            'vip_amount' => $validated['vip_amount'],
            '1st_class_amount' => $validated['1st_class_amount'],
        ]);

        $selectedBlocks = $request->input('blocks', []); // Array of seat_ids from checkboxes
        $totalTickets = 0;
        foreach ($selectedBlocks as $seatId) {
            $seat = Seat::find($seatId);
            $match->seats()->attach($seatId, ['available_tickets' => $seat->number_of_seats]);
            $totalTickets += $seat->number_of_seats;
        }
        // Save total_ticket_number as sum of available_tickets for all attached seats
        $match->total_ticket_number = $totalTickets;
        $match->save();

        $this->logCreate($match, "Created new match: {$match->home_team} vs {$match->away_team}");

        return redirect()->route('admin.matches.index')
            ->with('success', 'Match created successfully.');
    }

    public function show(MatchModel $match)
    {
        return view('admin.matches.show', compact('match'));
    }

    public function edit(MatchModel $match)
    {
        return view('admin.matches.edit', compact('match'));
    }

    public function update(Request $request, MatchModel $match)
    {
        $validated = $request->validate([
            'home_team' => 'required|string|max:100',
            'away_team' => 'required|string|max:100',
            'match_date' => 'required|date',
            'stadium' => 'required|string|max:100',
            'home_team_flag' => 'required|string|max:100',
            'away_team_flag' => 'required|string|max:100',
            'vvip_amount' => 'required|numeric|min:0',
            'vip_amount' => 'required|numeric|min:0',
            '1st_class_amount' => 'required|numeric|min:0',
            'total_ticket_number' => 'required|numeric|min:0',
        ]);

        $oldValues = $match->toArray();
        $match->update($validated);

        $this->logUpdate($match, $oldValues, "Updated match: {$match->home_team} vs {$match->away_team}");

        return redirect()->route('admin.matches.index')
            ->with('success', 'Match updated successfully.');
    }

    public function destroy(MatchModel $match)
    {
        $matchName = "{$match->home_team} vs {$match->away_team}";
        $this->logDelete($match, "Deleted match: {$matchName}");

        $match->delete();

        return redirect()->route('admin.matches.index')
            ->with('success', 'Match deleted successfully.');
    }
}
