<?php

namespace App\Repositories;

use App\DTOs\SalesChannel\SalesChannelCreateDto;
use App\DTOs\SalesChannel\SalesChannelUpdateDto;
use Exception;

use App\Models\SalesChannel;
use App\Repositories\Interfaces\ISalesChannelRepository;

class SalesChannelRepository implements ISalesChannelRepository
{
    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 = SalesChannel::where('status', '=', 1)->where('ruc', '=', $ruc)->orderBy($orderBy, $orderDir);
            if (isset($request['search'])) {
                $search = $request['search'];
                $query = $query->where('code', 'like', '%' . $search . '%')
                    ->orWhere('name', 'like', '%' . $search . '%');
            }
            $trader_count = $query->where('status', '=', 1)->where('ruc', '=', $ruc)->count();
            $traders = $query->skip($start)->take($length);
            $traders = $traders->where('status', '=', 1)->where('ruc', '=', $ruc)->get();
        } else {
            $ct = SalesChannel::where('status', '=', 1)->where('ruc', '=', $ruc);
            $trader_count = $ct->count();
            $traders = $ct->get();
        }
        $respuesta['total'] = $trader_count;
        $respuesta['list'] = $traders;

        return $respuesta;
    }

    public function find(int $id): ?SalesChannel
    {
        return SalesChannel::find($id);
    }

    public function store(SalesChannelCreateDto $store): SalesChannel
    {
        $entry = new SalesChannel();

        $entry->ruc = $store->ruc;
        $entry->code = $store->code;
        $entry->name = $store->name;
        $entry->description = $store->description;

        $entry->created_by = $store->created_by;
        $entry->save();

        return $entry;
    }

    public function update(SalesChannelUpdateDto $store): void
    {
        $entry = SalesChannel::find($store->id);
        
        $entry->code = $store->code;
        $entry->name = $store->name;
        $entry->description = $store->description;

        $entry->updated_by = $store->updated_by;

        $entry->save();
    }

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