<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\MatchModel;
use App\Models\Ticket;
use App\Models\TransactionModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class FanController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('fans.createaccount');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'phone' => 'required|unique:users|string|max:255',
            'password' => 'required|string|min:8',
        ]);

        $user = User::create([
            'phone' => $validatedData['phone'],
            'password_hash' => Hash::make($validatedData['password']),
            'role' => 'fan',
        ]);

        Auth::login($user);

        return redirect()->route('fans.profile');
    }

    /**
     * Display the fan's profile.
     *
     * @return \Illuminate\Http\Response
     */
    public function profile()
    {
        return view('fans.index');
    }

    public function fancreateticket()
    {
        $matches = MatchModel::with('seats')->get();
        return view('tickets.fancreateticket', compact('matches'));
    }

    public function fansdashboard()
    {
        $user = Auth::user();

        // My Tickets
        $myTickets = Ticket::where('user_id', $user->user_id)
            ->with(['match', 'seat'])
            ->orderBy('created_at', 'desc')
            ->get();

        // Total Spent
        $totalSpent = TransactionModel::where('user_id', $user->user_id)->sum('amount');
        $ticketsBoughtCount = $myTickets->count();

        // Upcoming Matches
        $upcomingMatches = MatchModel::where('match_date', '>', Carbon::now())
            ->with('seats')
            ->orderBy('match_date', 'asc')
            ->get();

        // Past Matches
        $pastMatches = MatchModel::where('match_date', '<=', Carbon::now())
            ->orderBy('match_date', 'desc')
            ->get();

        return view('fans.fansdashboard', compact('myTickets', 'totalSpent', 'ticketsBoughtCount', 'upcomingMatches', 'pastMatches'));
    }

    public function index()
    {
        return view('fans.index');
    }
    public function transactions()
    {
        $user = Auth::user();

        // Fetch all transactions for the authenticated user
        $transactions = TransactionModel::where('user_id', $user->user_id)
            ->with(['ticket.match', 'ticket.seat'])
            ->orderBy('created_at', 'desc')
            ->get();

        // Prepare data for spending patterns graph (e.g., monthly spending)
        $spendingData = $transactions->groupBy(function($date) {
            return \Carbon\Carbon::parse($date->created_at)->format('Y-m'); // Group by year-month
        })->map(function ($row) {
            return $row->sum('amount');
        })->sortKeys();

        $chartLabels = $spendingData->keys()->map(function ($month) {
            return \Carbon\Carbon::parse($month)->format('M Y');
        });
        $chartData = $spendingData->values();

        return view('fans.transactions', compact('transactions', 'chartLabels', 'chartData'));
    }
}
