<?php

namespace App\Http\Controllers\Api;

require_once app_path('Helpers/AcademicYearHelper.php');

use App\Http\Controllers\Controller;
use App\Models\Salle;
use App\Models\Localisation;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class SalleController extends Controller
{
    /**
     * Liste toutes les salles
     * GET /api/v1/salles
     */
    public function index(): JsonResponse
    {
        $salles = Salle::with('localisationRelation')->orderBy('nom', 'asc')->get();

        return response()->json([
            'success' => true,
            'data' => $salles,
            'count' => $salles->count()
        ]);
    }

    /**
     * Afficher une salle spécifique avec son planning
     * GET /api/v1/salles/{id}
     */
    public function show(int $id): JsonResponse
    {
        $salle = Salle::with([
            'emploisDuTemps' => function ($query) {
                $query->valide()
                    ->with(['ecuRelation', 'jourRelation'])
                    ->orderBy('jour', 'asc')
                    ->orderBy('heuredebut', 'asc');
            }
        ])->find($id);

        if (!$salle) {
            return response()->json([
                'success' => false,
                'message' => 'Salle non trouvée'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $salle
        ]);
    }

    /**
     * Create a new room
     * POST /api/v1/salles
     */
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'nom' => 'required|string|max:255',
            'longitude' => 'required|numeric',
            'latitude' => 'required|numeric',
            'annee_acad' => 'sometimes|integer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        $validated = $validator->validated();

        if (!isset($validated['annee_acad'])) {
            $validated['annee_acad'] = AcademicYear();
        }

        // Find or create localization
        $localisation = Localisation::firstOrCreate([
            'longitude' => $validated['longitude'],
            'latitude' => $validated['latitude'],
            'annee_acad' => $validated['annee_acad']
        ]);

        $salle = Salle::create([
            'nom' => $validated['nom'],
            'localisation' => $localisation->id,
            'annee_acad' => $validated['annee_acad']
        ]);

        return response()->json([
            'success' => true,
            'data' => $salle->load('localisationRelation'),
            'message' => 'Salle créée avec succès'
        ], 201);
    }

    /**
     * Update a room
     * PUT /api/v1/salles/{id}
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $salle = Salle::find($id);

        if (!$salle) {
            return response()->json([
                'success' => false,
                'message' => 'Salle non trouvée'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'nom' => 'sometimes|string|max:255',
            'longitude' => 'sometimes|numeric',
            'latitude' => 'sometimes|numeric',
            'annee_acad' => 'sometimes|integer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        $validated = $validator->validated();
        $updateData = [];

        if (isset($validated['nom']))
            $updateData['nom'] = $validated['nom'];
        if (isset($validated['annee_acad']))
            $updateData['annee_acad'] = $validated['annee_acad'];

        if (isset($validated['longitude']) || isset($validated['latitude'])) {
            $lon = $validated['longitude'] ?? ($salle->localisationRelation ? $salle->localisationRelation->longitude : 0);
            $lat = $validated['latitude'] ?? ($salle->localisationRelation ? $salle->localisationRelation->latitude : 0);
            $year = $validated['annee_acad'] ?? $salle->annee_acad;

            $localisation = Localisation::firstOrCreate([
                'longitude' => $lon,
                'latitude' => $lat,
                'annee_acad' => $year
            ]);
            $updateData['localisation'] = $localisation->id;
        }

        $salle->update($updateData);

        return response()->json([
            'success' => true,
            'data' => $salle->load('localisationRelation'),
            'message' => 'Salle mise à jour avec succès'
        ]);
    }

    /**
     * Delete a room
     * DELETE /api/v1/salles/{id}
     */
    public function destroy(int $id): JsonResponse
    {
        $salle = Salle::find($id);

        if (!$salle) {
            return response()->json([
                'success' => false,
                'message' => 'Salle non trouvée'
            ], 404);
        }

        // Check if room has schedule events? Maybe prevent delete if used.
// For now, allow delete (soft delete logic not enabled on model but let's assume standard delete)

        $salle->delete();

        return response()->json([
            'success' => true,
            'message' => 'Salle supprimée avec succès'
        ]);
    }
}