<?php

namespace App\Http\Controllers;

use App\Models\Cliente;
use App\Models\Expediente;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Validation\Rule;

class ClienteController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request): JsonResponse
    {
        $cliente=Cliente::with('direccionesEntrega')->with('datosFiscales')
        ->leftjoin('expedientes', 'expedientes.cliente_id', '=', 'clientes.id')
        ->selectRaw("
            clientes.id,
            clientes.razonSocial,
            clientes.email,
            clientes.celular,
            clientes.observacion,
            count(expedientes.id) count_exp
        ")
        ->where(['clientes.estatus'=>'activo'])
        ->when($request->search,function (Builder $builder) use ($request) {
            $builder->where(function($query) use ($request) {
                $query->where('clientes.id', 'like', "%{$request->search}%")
                    ->orWhere('clientes.razonSocial', 'like', "%{$request->search}%")
                    ->orWhere('clientes.email', 'like', "%{$request->search}%")
                    ->orWhere('clientes.celular', 'like', "%{$request->search}%");
            });
        })
        ->groupBy(['clientes.id','clientes.razonSocial','clientes.email','clientes.celular','clientes.observacion'])
        ->orderBy($request->order['name'],$request->order['order'])->paginate($request->perPage);
        return response()->json([
            'data' =>$cliente,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'razonSocial' => ['required', 'string', 'max:250'],
            'celular' => ['max:45'],
            'email' => ['required', 'email',Rule::unique('clientes')->ignore('inactivo','estatus')]
        ]);

        $cliente = Cliente::create($request->only([
            'rfc',
            'razonSocial',
            'celular',
            'email',
            'observacion'
        ]));

        return response()->json([
            'data' => $cliente,
        ], JsonResponse::HTTP_OK);
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Cliente $cliente): JsonResponse
    {
        return response()->json([
            'data' => $cliente,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Cliente $cliente): JsonResponse
    {
        $request->validate([
            'razonSocial' => ['required', 'string', 'max:250'],
            'celular' => ['max:45'],
            'email' => ['required', 'email',Rule::unique('clientes')->where(function ($query) use ($cliente) {
                $query->whereNotIn('id', [$cliente->id])->whereNotIn('estatus', ['inactivo']);
                return $query;
            })]
        ]);

        $cliente->update($request->only([
            'rfc',
            'razonSocial',
            'celular',
            'email',
            'observacion'
        ]));

        return response()->json([
            'data' => $cliente,
        ], JsonResponse::HTTP_OK);
    }

    public function getExpedientes(Request $request, Cliente $cliente): JsonResponse
    {
        $expedientes = Expediente::leftjoin('sucursales', 'expedientes.sucursal_id', '=', 'sucursales.id')
        ->selectRaw("
            expedientes.*,
            date_format(expedientes.fecha_registro,'%d-%m-%Y %l %p') fecha_registro,
            sucursales.nombre sucursal
        ")
        ->when($request->sucursal_id,function (Builder $builder) use ($request) {
            $builder->Where('sucursales.id', 'like', "%{$request->sucursal_id}%");
        })
        ->where(['cliente_id'=>$cliente->id])
        ->orderByDesc('expedientes.fecha_registro')->get();
        return response()->json([
            'data' =>$expedientes,
        ], JsonResponse::HTTP_OK);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Cliente $cliente): JsonResponse
    {
        if (
            \count($cliente->expedientes) > 0 ||
            \count($cliente->ventas) > 0 ||
            \count($cliente->sesiones) > 0 ||
            \count($cliente->user) > 0 ||
            \count($cliente->direccionesEntrega) > 0 ||
            \count($cliente->datosFiscales) > 0 ||
            \count($cliente->fiscales) > 0
        ) {
            $cliente->update([
                'estatus' => 'inactivo',
            ]);
        } else {
            $cliente->delete();
        }

        return response()->json(null, JsonResponse::HTTP_NO_CONTENT);
    }

    public function search(Request $request): JsonResponse
    {
        $cliente=[];
        if(!empty($request->search)){
            $cliente=Cliente::where(['clientes.estatus'=>'activo'])
                ->where(function($query) use ($request) {
                    $query->where('razonSocial','LIKE',"%{$request->search}%")
                        ->orWhere('celular','LIKE',"%{$request->search}%")
                        ->orWhere('email','LIKE',"%{$request->search}%")
                        ->orWhere('id','LIKE',"%{$request->search}%");
                })
                ->get()
                ->load('user.tiendas');
        }
        return response()->json([
            'data' =>$cliente,
        ], JsonResponse::HTTP_OK);
    }
}
