<?php

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

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

class ClientController extends Controller
{
    /**
     * Display a listing of clients assigned to the authenticated user.
     * Regular users can only see clients assigned to them.
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $userId = $request->user()->id;

        $query = Client::with(['creator:id,name,email'])
            ->where('assigned_to', $userId);

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

        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);
    }

    /**
     * Display the specified client.
     * User can only view clients assigned to them.
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Cms\Client  $client
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Request $request, Client $client): JsonResponse
    {
        $userId = $request->user()->id;

        // Check if this client is assigned to the authenticated user
        if ($client->assigned_to !== $userId) {
            return response()->json([
                'message' => 'Access denied. This client is not assigned to you.',
            ], 403);
        }

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

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