<?php

namespace HelpGent\App\Repositories;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\DTO\ContactInfoDTO;
use HelpGent\App\Models\ContactInfo;
use HelpGent\WpMVC\Repositories\Repository;
use HelpGent\WpMVC\Database\Query\Builder;

class ContactInfoRepository extends Repository{
    public function get_query_builder(): Builder {
        return ContactInfo::query( 'contact_info' );
    }

    public function get_response_contact_info( int $response_id ) {
        return $this->get_query_builder()->where_null( 'answer_id' )->where( 'is_lead', 1 )->where( 'response_id', $response_id )->first();
    }

    public function get_response_contact_infos( array $response_ids ): array {
        $response_ids = array_values(
            array_unique(
                array_filter(
                    array_map( 'intval', $response_ids )
                )
            )
        );

        if ( empty( $response_ids ) ) {
            return [];
        }

        $contact_infos = $this->get_query_builder()
            ->where_null( 'answer_id' )
            ->where( 'is_lead', 1 )
            ->where_in( 'response_id', $response_ids )
            ->get();

        $indexed_contact_infos = [];

        foreach ( $contact_infos as $contact_info ) {
            $indexed_contact_infos[ intval( $contact_info->response_id ) ] = $contact_info;
        }

        return $indexed_contact_infos;
    }

    /**
     * Create multiple items
     */
    public function creates( ContactInfoDTO ...$items ) {
        return ContactInfo::query()->insert(
            array_map(
                function( ContactInfoDTO $item ) {
                    $values               = $item->to_array();
                    $values['created_at'] = helpgent_now();
                    return $values;
                }, $items
            )
        );
    }
}
