<?php
namespace App\Repositories;

use Exception;
use App\Models\CustomerType;
use App\DTOs\CustomerType\CustomerTypeCreateDto;
use App\DTOs\CustomerType\CustomerTypeUpdateDto;
use App\Models\Customer;
use App\Repositories\Interfaces\ICustomerTypeRepository;

class CustomerTypeRepository implements ICustomerTypeRepository
{
    public function paginate(array $request)
    {
        $business_information = $request['business_information'];
        $ruc = $business_information['ruc_number'];
        if ((isset($request['search'])) || (isset($request['orderby'])) || (isset($request['orderdir'])) || (isset($request['start'])) || (isset($request['length']))) {
            $orderBy = $request['orderby'];
            $orderDir = $request['orderdir'];
            $start = $request['start'];
            $length = $request['length'];
            $query = CustomerType::where('status', '=', 1)->where('ruc', '=', $ruc)->orderBy($orderBy, $orderDir);
            if (isset($request['search'])) {
                $search = $request['search'];
                $query = $query->where('customers_type', 'like', '%' . $search . '%');
            }
            $customertype_count = $query->where('status', '=', 1)->where('ruc', '=', $ruc)->count();
            $customertype = $query->skip($start)->take($length);
            $customertype = $customertype->where('status', '=', 1)->where('ruc', '=', $ruc)->get();
        } else {
            $ct = CustomerType::where('status', '=', 1)->where('ruc', '=', $ruc);
            $customertype_count = $ct->count();
            $customertype = $ct->get();
        }
        $respuesta['total'] = $customertype_count;
        $respuesta['list'] = $customertype;

        return $respuesta;
    }

    public function find(int $id, string $business_ruc): ?CustomerType
    {
        return CustomerType::where('ruc',$business_ruc)->where('status',1)->find($id);
    }

    public function store(CustomerTypeCreateDto $store): CustomerType
    {
        $entry = new CustomerType();

        $entry->ruc = $store->ruc;
        $entry->customers_type = $store->customers_type;
        $entry->created_by = $store->created_by;
        $entry->updated_by = $store->updated_by;
        $entry->created_at = $store->created_at;
        $entry->updated_at = $store->updated_at;
        $entry->status = $store->status;

        $entry->save();

        return $entry;
    }

    public function update(CustomerTypeUpdateDto $store): void
    {
        $entry = CustomerType::where('ruc',$store->ruc)->find($store->id);

        $entry->ruc = $store->ruc;
        $entry->customers_type = $store->customers_type;
        $entry->updated_by = $store->updated_by;
        $entry->updated_at = $store->updated_at;
        $entry->status = $store->status;


        $entry->save();
    }

    public function destroy(int $id): void
    {
        CustomerType::where('id',$id)->update([
            'status' => 0
        ]);
    }
}
