<?php

namespace App\Http\Controllers;

use App\Models\Appointment;
use App\Models\AppointmentPhoto;
use App\Models\CustomServiceLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ClientAdminController extends Controller
{
    /**
     * List client users. Optional `q` filters by name, email, or phone.
     * Use `active_only=1` when picking a client for a new appointment (manual booking).
     */
    public function index(Request $request)
    {
        $q = trim((string) $request->query('q', ''));

        $query = User::where('role', 'client');

        if ($request->boolean('active_only')) {
            $query->where('is_active', true);
        }

        if ($q !== '') {
            $query->whereClientSearch($q);
        }

        $clients = $query
            ->orderBy('name')
            ->limit(200)
            ->get(['id', 'name', 'email', 'phone', 'is_active', 'created_at']);

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

    /**
     * Create a new client.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:6',
            'phone' => 'nullable|string|max:20',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'role' => 'client',
            'is_active' => true,
        ]);

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

    /**
     * Update a client.
     */
    public function update(Request $request, int $id)
    {
        $user = User::where('id', $id)->where('role', 'client')->firstOrFail();

        $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'email' => 'sometimes|required|email|unique:users,email,' . $id,
            'phone' => 'nullable|string|max:20',
            'password' => 'nullable|string|min:6',
            'is_active' => 'sometimes|boolean',
        ]);

        $data = [
            'name' => $request->get('name', $user->name),
            'email' => $request->get('email', $user->email),
            'phone' => $request->get('phone', $user->phone),
        ];
        if ($request->has('is_active')) {
            $data['is_active'] = $request->boolean('is_active');
        }

        if ($request->filled('password')) {
            $data['password'] = Hash::make($request->password);
        }

        $user->update($data);
        return response()->json($user);
    }

    /**
     * Full client expediente: appointment history (all statuses) and photos.
     */
    public function expediente(int $id)
    {
        User::where('id', $id)->where('role', 'client')->firstOrFail();

        $appointments = Appointment::with(['barber.user', 'service', 'photos'])
            ->where('client_id', $id)
            ->orderBy('appointment_date', 'desc')
            ->orderBy('start_time', 'desc')
            ->get();

        $photos = AppointmentPhoto::with(['appointment.service', 'appointment.barber.user'])
            ->whereHas('appointment', fn ($q) => $q->where('client_id', $id))
            ->orderBy('taken_at', 'desc')
            ->get();

        $customServiceLogs = CustomServiceLog::with('barber.user')
            ->where('client_id', $id)
            ->orderBy('service_date', 'desc')
            ->orderBy('start_time', 'desc')
            ->get();

        return response()->json([
            'appointments' => $appointments,
            'photos' => $photos,
            'custom_service_logs' => $customServiceLogs,
        ]);
    }

    /**
     * Actualizar un registro de servicio especial vinculado a un cliente.
     */
    public function updateCustomServiceLog(Request $request, int $clientId, int $logId)
    {
        User::where('id', $clientId)->where('role', 'client')->firstOrFail();

        $log = CustomServiceLog::with('barber')
            ->where('id', $logId)
            ->where('client_id', $clientId)
            ->firstOrFail();

        $validated = $request->validate([
            'description' => 'required|string|max:500',
            'client_name' => 'nullable|string|max:200',
            'service_date' => 'required|date',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'price' => 'required|numeric|min:0',
        ]);

        $log->update($validated);

        return response()->json($log->fresh()->load('barber.user'));
    }

    /**
     * Eliminar un registro de servicio especial del expediente.
     */
    public function deleteCustomServiceLog(int $clientId, int $logId)
    {
        User::where('id', $clientId)->where('role', 'client')->firstOrFail();

        $log = CustomServiceLog::where('id', $logId)
            ->where('client_id', $clientId)
            ->firstOrFail();

        $log->delete();

        return response()->json(['message' => 'Registro eliminado.']);
    }

    /**
     * Delete a photo from a client's expediente (admin only).
     */
    public function deletePhoto(int $photoId)
    {
        $photo = AppointmentPhoto::findOrFail($photoId);
        if ($photo->file_path && Storage::disk('photos')->exists($photo->file_path)) {
            Storage::disk('photos')->delete($photo->file_path);
        }
        $photo->delete();
        return response()->json(['message' => 'Photo deleted']);
    }

    /**
     * Deactivate client (soft delete - set is_active = false).
     */
    public function destroy(int $id)
    {
        $user = User::where('id', $id)->where('role', 'client')->firstOrFail();
        $user->update(['is_active' => false]);
        return response()->json(['message' => 'Client deactivated']);
    }
}
