<?php

namespace App\Services;

use App\Customer;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;
use App\Traits\ServiceAppAop;


class CustomerService
{
    use ServiceAppAop;
    protected $modelClass=Customer::class;
    public function getSelection($column = ['id', 'name'])
    {
        return Customer::query()->select($column)->get();
    }

    public function paginate(array $params, array $withs=[])
    {
        $query = Customer::query()->with($withs)->orderByDesc('id');
        if ($params["tags"] ?? false){
            $query->whereHas("tags",function ($builder)use($params){
                /** @var Builder $builder */
                $builder->whereIn("id",explode(",",$params["tags"]));
            });
            unset($params["tags"]);
        }
        $columnQueryRules=[
            'company_name' => ['like' => ''],
            'contact_man' => ['like' => ''],
            'phone' => ['like' => ''],
        ];
        /** @var Builder $query */
        $query = app(QueryService::class)->query($params,$query,$columnQueryRules,"customers");
        return $query->paginate($params["paginate"] ?? 50);
    }

    public function create(array $params)
    {
        return Customer::query()->create($params);
    }

    public function find($id)
    {
        return Customer::query()->find($id);
    }

    public function update(array $params, array $values)
    {
        $query = Customer::query();
        foreach ($params as $column => $value){
            $query->where($column,$value);
        }
        return $query->update($values);
    }

    public function destroy($id)
    {
        return Customer::destroy($id);
    }
}
