<?php

namespace App\Http\Controllers;

use App\Models\Eleve;
use App\Models\Classe;
use App\Models\Score;

use Illuminate\Http\Request;

class EleveController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $eleves = Eleve::with(['classes', 'scores'])->get();
        $classes = Classe::all();
        return view('eleves.index', compact('eleves','classes'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('eleves.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name'  => 'required|string|max:255',
            'last_name'   => 'required|string|max:255',
            'email'       => 'nullable|string',
            'date'        => 'required',
            'phone'       => 'nullable|string|max:20',
            'class_ids'   => 'required|array',
            'moyenne_t1'  => 'nullable|numeric|min:0|max:20',
            'moyenne_t2'  => 'nullable|numeric|min:0|max:20',
        ]);

        $eleve = Eleve::create($validated);
        $eleve->classes()->attach($request->class_ids);

        $classeId = $request->class_ids[0] ?? null;

        foreach ([1 => $request->moyenne_t1, 2 => $request->moyenne_t2] as $type => $average) {
            if ($average !== null && $average !== '') {
                Score::create([
                    'name'       => $type === 1 ? 'الثلاثي الأول' : 'الثلاثي الثاني',
                    'type'       => $type,
                    'average'    => $average,
                    'eleve_id'   => $eleve->id,
                    'classe_id'  => $classeId,
                    'coefficient'=> 1,
                    'rank'       => 0,
                    'sum'        => $average,
                    'sum_coeff'  => 1,
                    'dispenser'  => false,
                ]);

                $this->recalculateRanks($type, $classeId);
            }
        }

        return redirect()->route('eleves.index')->with('success', 'Eleve created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Eleve $eleve)
    {
        return view('eleves.show', compact('eleve'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Eleve $eleve)
    {
        return view('eleves.edit', compact('eleve'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Eleve $eleve)
    {
        $validated = $request->validate([
            'first_name' => 'nullable',
            'last_name'  => 'nullable',
            'email'      => 'nullable',
            'date'       => 'nullable',
            'phone'      => 'nullable',
            'code'       => 'nullable',
            'moyenne_t1' => 'nullable|numeric|min:0|max:20',
            'moyenne_t2' => 'nullable|numeric|min:0|max:20',
        ]);

        $eleve->update($validated);

        $classeId = $eleve->classes()->first()?->id;

        foreach ([1 => $request->moyenne_t1, 2 => $request->moyenne_t2] as $type => $average) {
            if ($average !== null && $average !== '') {
                Score::updateOrCreate(
                    ['eleve_id' => $eleve->id, 'type' => $type],
                    [
                        'name'       => $type === 1 ? 'الثلاثي الأول' : 'الثلاثي الثاني',
                        'average'    => $average,
                        'classe_id'  => $classeId,
                        'coefficient'=> 1,
                        'rank'       => 0,
                        'sum'        => $average,
                        'sum_coeff'  => 1,
                        'dispenser'  => false,
                    ]
                );

                $this->recalculateRanks($type, $classeId);
            }
        }

        return redirect()->route('eleves.index')->with('success', 'Eleve updated successfully.');
    }
    

    private function recalculateRanks(int $type, ?int $classeId): void
    {
        $scores = Score::where('type', $type)
            ->where('classe_id', $classeId)
            ->orderByDesc('average')
            ->get();

        $rank = 1;
        foreach ($scores as $score) {
            $score->rank = $rank++;
            $score->save();
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Eleve $eleve)
    {
        $eleve->delete();

        return redirect()->route('eleves.index')->with('success', 'Eleve deleted successfully.');
    }
}
