<?php //phpcs:ignore Internal.Exception

namespace Vendtics\App\Repositories;

defined( "ABSPATH" ) || exit;

use Vendtics\WpMVC\Database\Query\Builder;
use Vendtics\WpMVC\Exceptions\Exception;
use Vendtics\App\Models\ListModel;
use Vendtics\App\DTO\Contact\ListDTO;
use Vendtics\App\DTO\Contact\ListReadDTO;
use Vendtics\WpMVC\DTO\DTO;

class ListRepository extends Repository {
    public function get_query_builder(): Builder {
        return ListModel::query( 'list' );
    }

    public function get( ListReadDTO $dto ) {
        $query = $this->get_query_builder();


        $this->list_search_query( $query, $dto );

        $count_query = clone $query;

        $this->lists_orders_query( $query, $dto )->select( 'list.*' )->with_count(
            'contacts as total_contacts', function( $query ) {
                $query->where( 'entity_type', 'contacts' );
            } 
        );

        return [
            'lists' => $query->pagination( $dto->get_page(), $dto->get_per_page() ),
            'total' => $count_query->count(),
        ];
    }

    protected function list_search_query( Builder $query, ListReadDTO $dto ) {
        if ( ! $dto->is_initialized( 'search' ) ) {
            return;
        }

        $search = $dto->get_search();

        if ( empty( $search ) ) {
            return;
        }

        $query->where(
            function( $like_query ) use( $search ) {
                $columns = [
                    'list.name',
                    'list.description'
                ];

                foreach ( $columns as $column ) {
                    $like_query->or_where_like( $column, "%{$search}%" );
                }
            }
        );
    }

    protected function lists_orders_query( Builder $query, ListReadDTO $dto ) {
        $order_columns =  [
            'id',
            'name',
            'description',
        ];

        if ( $dto->get_orders() ) {
            foreach ( $dto->get_orders() as $order ) {
                if ( empty( $order['order'] ) || empty( $order['order_by'] ) ) {
                    continue;
                }

                if ( ! in_array( $order['order_by'], $order_columns, true ) || ! in_array( $order['order'], ['asc', 'desc'], true ) ) {
                    continue;
                }

                $query->order_by( "list.{$order['order_by']}", $order['order'] );
            }
        } else {
            $query->order_by( "list.id", 'desc' );
        }

        return $query;
    }

    /**
     * @var ListDTO $dto
     */
    public function create( DTO $dto ) {
        /**
         * @var ListDTO $dto
         */
        $contact = $this->get_by( "name", $dto->get_name() );

        $this->throw_name_already_exists( $contact );

        return parent::create( $dto );
    }

     /**
     * @var ListDTO $dto
     */
    public function update( DTO $dto ) {
        /**
         * @var ListDTO $dto
         */
        $contact = $this->get_by_id( $dto->get_id() );

        if ( ! $contact ) {
            throw (new Exception( esc_html__( 'The list not found.', 'vendtics' ), 404 ));
        }

        if ( $contact->name !== $dto->get_name() ) {
            $name_contact = $this->get_by( "name", $dto->get_name() );

            $this->throw_name_already_exists( $name_contact );
        }

        return parent::update( $dto );
    }

    private function throw_name_already_exists( $contact ) {
        if ( $contact ) {
            throw (new Exception( '', 422 ))->set_messages(
                [
                    "name" => [
                        esc_html__( "The name already exists.", 'vendtics' )
                    ]
                ]
            );
        }
    }

    public function select() {
        return ListModel::query()->select( 'id', 'name' )->get();
    }

    public function count() {
        return ListModel::query()->count();
    }
}