<?php

namespace App\Services;

use App\Models\Client;

class ClientService
{
    public function list($request)
    {
        $query = Client::query();

        if($request->filled('search')){

            $query->where(function($q) use($request){

                $q->where('client_name','like','%'.$request->search.'%')
                  ->orWhere('client_code','like','%'.$request->search.'%')
                  ->orWhere('mobile','like','%'.$request->search.'%');

            });

        }

        if($request->filled('status')){
            $query->where('status',$request->status);
        }

        if($request->filled('city')){
            $query->where('city',$request->city);
        }

        return $query
            ->latest()
            ->paginate(10);
    }

   public function store($request)
    {
        $data = $request->validated();
    
        $data['credit_limit'] = $data['credit_limit'] ?? 0;
    
        $data['opening_balance'] = $data['opening_balance'] ?? 0;
    
        $data['created_by'] = auth()->id();
    
        $client = Client::create($data);
    
        $client->update([
            'client_code' => 'CL' . str_pad($client->id, 6, '0', STR_PAD_LEFT)
        ]);
    
        return $client->fresh();
    }

    public function update($request,Client $client)
    {
        $data = $request->validated();

        $data['updated_by']=auth()->id();
        $data['credit_limit'] = $data['credit_limit'] ?? 0;
    
        $data['opening_balance'] = $data['opening_balance'] ?? 0;

        $client->update($data);

        return $client->refresh();
    }

    public function delete(Client $client)
    {
        $client->delete();
    }

    public function restore($id)
    {
        $client=Client::onlyTrashed()->findOrFail($id);

        $client->restore();

        return $client;
    }

    public function forceDelete($id)
    {
        Client::onlyTrashed()->findOrFail($id)->forceDelete();
    }
    
    private function generateClientCode()
    {
        $lastClient = Client::withTrashed()
            ->latest('id')
            ->first();
    
        $number = $lastClient ? ($lastClient->id + 1) : 1;
    
        return 'CL' . str_pad($number, 6, '0', STR_PAD_LEFT);
    }

}