<?php

namespace Vendtics\App\Repositories;

defined( "ABSPATH" ) || exit;

use stdClass;
use Vendtics\App\Models\EntityTag;
use Vendtics\App\Models\EntityList;
use Vendtics\App\Models\Contact;
use Vendtics\App\Models\Segment;
use Vendtics\WpMVC\Database\Query\Builder;
use Vendtics\WpMVC\Exceptions\Exception;
use Vendtics\App\Models\CampaignRecipient;

class CampaignRecipientRepository extends Repository {

    use AdvancedFilter;

    public function get_query_builder(): Builder {
        return CampaignRecipient::query();
    }

    public function get_recipient_query( stdClass $campaign ) {
        $query = Contact::query( 'contact' );

        if ( 'segment' === $campaign->recipient_type ) {
            $segment = Segment::query()->select( 'queries' )->where( 'id', absint( $campaign->segment_id ) )->first();

            if ( ! $segment ) {
                throw new Exception( esc_html__( "Segment not found", 'vendtics' ) );   
            }

            return $this->advanced_filter_query( $query, json_decode( $segment->queries, true ) );
        }

        if ( 'advanced_filter' === $campaign->recipient_type ) {
            return $this->advanced_filter_query( $query, json_decode( $campaign->advanced_filters, true ) );
        }

        $tag_ids  = wp_list_pluck( EntityTag::query()->where( 'entity_type', 'campaigns' )->select( 'tag_id' )->where( 'entity_id', $campaign->id )->get(), 'tag_id' );
        $list_ids = wp_list_pluck( EntityList::query()->where( 'entity_type', 'campaigns' )->select( 'list_id' )->where( 'entity_id', $campaign->id )->get(), 'list_id' );

        if ( ! empty( $tag_ids ) ) {
            $query->join(
                EntityList::get_table_name() . ' as entity_tag', function( $join ) use( $tag_ids ) {
                    $join->on_column( 'entity_tag.entity_id', 'contact.id' )->on_in( 'entity_tag.tag_id', $tag_ids )->on( "entity_tag.entity_type", "campaigns" );
                } 
            );
        }

        if ( ! empty( $list_ids ) ) {
            $query->join(
                EntityList::get_table_name() . ' as entity_list', function( $join ) use( $list_ids ){
                    $join->on_column( 'entity_list.entity_id', 'contact.id' )->on_in( 'entity_list.list_id', $list_ids )->on( "entity_list.entity_type", "campaigns" );
                } 
            );
        }

        return $query->where( 'contact.status', 'subscribe' );
    }
}