<?php

namespace App\Http\Controllers;

use App\Models\Trainer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class TrainerController extends Controller
{
    public function index()
    {
        return Trainer::orderBy('last_name')->paginate(15);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|unique:trainers,email',
            'phone' => 'nullable|string',
            'specialization' => 'required|string',
            'hire_date' => 'required|date',
            'certifications' => 'nullable|string',
            'profile_image' => 'nullable|image|max:2048',
            'status' => 'required|in:active,inactive',
        ]);

        if ($request->hasFile('profile_image')) {
            $validated['profile_image'] = $request->file('profile_image')->store('trainer-profiles', 'public');
        }

        $trainer = Trainer::create($validated);

        return response()->json($trainer, 201);
    }

    public function show($id)
    {
        return Trainer::findOrFail($id);
    }

    public function update(Request $request, $id)
    {
        $trainer = Trainer::findOrFail($id);
        
        $validated = $request->validate([
            'first_name' => 'sometimes|string|max:255',
            'last_name' => 'sometimes|string|max:255',
            'email' => 'sometimes|email|unique:trainers,email,'.$id,
            'phone' => 'nullable|string',
            'specialization' => 'sometimes|string',
            'hire_date' => 'sometimes|date',
            'certifications' => 'nullable|string',
            'profile_image' => 'nullable|image|max:2048',
            'status' => 'sometimes|in:active,inactive',
        ]);

        if ($request->hasFile('profile_image')) {
            // Delete old image if exists
            if ($trainer->profile_image) {
                Storage::disk('public')->delete($trainer->profile_image);
            }
            $validated['profile_image'] = $request->file('profile_image')->store('trainer-profiles', 'public');
        }

        $trainer->update($validated);

        return response()->json($trainer);
    }

    public function destroy($id)
    {
        $trainer = Trainer::findOrFail($id);
        
        // Delete profile image if exists
        if ($trainer->profile_image) {
            Storage::disk('public')->delete($trainer->profile_image);
        }
        
        $trainer->delete();
        
        return response()->json(null, 204);
    }
}