<?php

namespace App\Http\Controllers\Api\V1\Cms\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cms\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class ClientController extends Controller
{
    /**
     * Display a listing of all clients.
     * Module admins can see all clients.
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $query = Client::with(['creator:id,name,email', 'assignedUser:id,name,email']);

        // Apply filters
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        if ($request->has('assigned_to')) {
            $query->where('assigned_to', $request->assigned_to);
        }

        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('company', 'like', "%{$search}%");
            });
        }

        // Sorting
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        // Pagination
        $perPage = $request->get('per_page', 15);
        $clients = $query->paginate($perPage);

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

    /**
     * Store a newly created client.
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'case_type' => 'nullable|string|max:100',
            'company' => 'nullable|string|max:255',
            'status' => 'nullable|in:active,inactive,archived',
            'assigned_to' => 'nullable|exists:users,id',
            'notes' => 'nullable|string',
        ]);

        // Set default status to active if not provided
        if (!isset($validated['status'])) {
            $validated['status'] = 'active';
        }

        $validated['created_by'] = $request->user()->id;

        $client = Client::create($validated);
        $client->load(['creator:id,name,email', 'assignedUser:id,name,email']);

        return response()->json([
            'message' => 'Client created successfully.',
            'client' => $client,
        ], 201);
    }

    /**
     * Display the specified client.
     * 
     * @param  \App\Models\Cms\Client  $client
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Client $client): JsonResponse
    {
        $client->load(['creator:id,name,email', 'assignedUser:id,name,email']);

        return response()->json([
            'client' => $client,
        ]);
    }

    /**
     * Update the specified client.
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Cms\Client  $client
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Client $client): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'email' => 'sometimes|required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'company' => 'nullable|string|max:255',
            'status' => 'sometimes|required|in:active,inactive,archived',
            'assigned_to' => 'nullable|exists:users,id',
            'notes' => 'nullable|string',
        ]);

        $client->update($validated);
        $client->load(['creator:id,name,email', 'assignedUser:id,name,email']);

        return response()->json([
            'message' => 'Client updated successfully.',
            'client' => $client,
        ]);
    }

    /**
     * Remove the specified client.
     * 
     * @param  \App\Models\Cms\Client  $client
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Client $client): JsonResponse
    {
        $client->delete();

        return response()->json([
            'message' => 'Client deleted successfully.',
        ]);
    }

    /**
     * Assign client to a user.
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Cms\Client  $client
     * @return \Illuminate\Http\JsonResponse
     */
    public function assignToUser(Request $request, Client $client): JsonResponse
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);

        $client->update(['assigned_to' => $validated['user_id']]);
        $client->load(['creator:id,name,email', 'assignedUser:id,name,email']);

        return response()->json([
            'message' => 'Client assigned successfully.',
            'client' => $client,
        ]);
    }
}
