<?php

namespace App\Http\Controllers\Provider;

use App\Http\Controllers\Controller;
use App\Http\Requests\ClientStoreRequest;
use App\Http\Requests\ClientUpdateRequest;
use App\Models\Client;
use Illuminate\Http\Request;

class ClientController extends Controller
{
    /**
     * Display a listing of the provider's clients.
     */
    public function index(Request $request)
    {
        $provider = auth()->user()->provider;
        $showArchived = $request->boolean('archived');
        
        $query = $showArchived 
            ? $provider->clients()->onlyTrashed()
            : $provider->clients();
            
        $query->when($request->search, function ($q, $search) {
                $q->where(function ($query) use ($search) {
                    $query->where('first_name', 'like', "%{$search}%")
                          ->orWhere('last_name', 'like', "%{$search}%")
                          ->orWhere('phone', 'like', "%{$search}%")
                          ->orWhere('email', 'like', "%{$search}%");
                });
            })
            ->withCount([
                'appointments',
                'appointments as scheduled_count' => function($q) {
                    $q->where('status', 'scheduled');
                },
                'appointments as complete_count' => function($q) {
                    $q->where('status', 'complete');
                },
                'appointments as cancelled_count' => function($q) {
                    $q->where('status', 'cancelled');
                }
            ])
            ->with(['appointments' => function($q) {
                $q->select('id', 'client_id', 'start_time', 'status')
                  ->whereIn('status', ['complete', 'scheduled'])
                  ->orderBy('start_time', 'desc');
            }])
            ->orderBy('created_at', 'desc');

        $clients = $query->paginate(15);
        
        // Calculer la dernière visite et prochaine visite pour chaque client
        $clients->getCollection()->transform(function ($client) {
            $lastCompleted = $client->appointments->where('status', 'complete')->sortByDesc('start_time')->first();
            $nextScheduled = $client->appointments->where('status', 'scheduled')->where('start_time', '>', now())->sortBy('start_time')->first();
            
            $client->last_visit_at = $lastCompleted ? $lastCompleted->start_time : null;
            $client->next_visit_at = $nextScheduled ? $nextScheduled->start_time : null;
            
            return $client;
        });

        return view('provider.clients.index', compact('clients', 'showArchived'));
    }

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

    /**
     * Store a newly created client.
     */
    public function store(ClientStoreRequest $request)
    {
        $provider = auth()->user()->provider;
        
        $client = $provider->clients()->create($request->validated());

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true, 
                'client' => [
                    'id' => $client->id,
                    'first_name' => $client->first_name,
                    'last_name' => $client->last_name
                ]
            ]);
        }

        return redirect()->route('provider.clients.index')
            ->with('success', 'Client créé avec succès.');
    }

    /**
     * Display the specified client.
     */
    public function show($client_uuid)
    {
        $client = $this->findClientByUuid($client_uuid);
        $client->load(['payments', 'appointments.service', 'appointments.payments']);
        
        return view('provider.clients.show', compact('client'));
    }

    /**
     * Show the form for editing the specified client.
     */
    public function edit($client_uuid)
    {
        $client = $this->findClientByUuid($client_uuid);
        
        return view('provider.clients.edit', compact('client'));
    }

    /**
     * Update the specified client.
     */
    public function update(ClientUpdateRequest $request, $client_uuid)
    {
        $client = $this->findClientByUuid($client_uuid);
        
        $client->update($request->validated());

        // Rediriger vers l'aperçu si on vient de là, sinon vers la liste
        $redirectTo = $request->input('redirect_to') === 'show' 
            ? route('provider.clients.show', $client->uuid)
            : route('provider.clients.index');

        return redirect($redirectTo)
            ->with('success', 'Client modifié avec succès.');
    }

    /**
     * Remove the specified client (soft delete).
     */
    public function destroy($client_uuid)
    {
        $client = $this->findClientByUuid($client_uuid);
        
        $client->delete();

        return redirect()->route('provider.clients.index')
            ->with('success', 'Client archivé avec succès.');
    }

    /**
     * Restore an archived client.
     */
    public function restore($client_uuid)
    {
        $provider = auth()->user()->provider;
        
        $client = $provider->clients()
            ->onlyTrashed()
            ->where('uuid', $client_uuid)
            ->firstOrFail();
            
        $client->restore();

        return redirect()->route('provider.clients.index', ['archived' => 1])
            ->with('success', 'Client restauré avec succès.');
    }

    /**
     * Find client by UUID ensuring it belongs to the authenticated provider.
     */
    private function findClientByUuid($client_uuid)
    {
        $provider = auth()->user()->provider;
        
        return $provider->clients()
            ->where('uuid', $client_uuid)
            ->firstOrFail();
    }
}
