<?php

namespace Vendtics\App\Http\Controllers\Admin;


defined( "ABSPATH" ) || exit;

use Vendtics\App\Repositories\CampaignRepository;
use Vendtics\App\Models\CampaignRecipient;
use Vendtics\App\Repositories\ContactRepository;
use Vendtics\App\Http\Controllers\Controller;
use Vendtics\WpMVC\Exceptions\Exception;
use Vendtics\WpMVC\Routing\Response;
use Vendtics\WpMVC\RequestValidator\Validator;
use WP_REST_Request;

class CampaignRecipientController extends Controller {
    public ContactRepository $contact_repository;

    public CampaignRepository $campaign_repository;

    public function __construct( ContactRepository $contact_repository, CampaignRepository $campaign_repository ) {
        $this->contact_repository  = $contact_repository;
        $this->campaign_repository = $campaign_repository;
    }

    /**
     * Display a listing of the resource.
     *
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function index( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                "id"       => "required|numeric",
                'page'     => 'required|numeric',
                'per_page' => 'required|numeric',
            ]
        );
    
        $recipients = CampaignRecipient::query()->where( 'campaign_id', intval( $request->get_param( 'id' ) ) );
        
        $count_query = clone $recipients;

        $recipients->with(
            'contact', function( $query ) {
                $query->select( 'id', 'first_name', 'last_name', 'email' );
            }
        );

        $recipients = array_map(
            function( $recipient ) {
                $recipient->contact->avatar_url = get_avatar_url( $recipient->contact->email );
                return $recipient;
            }, $recipients->pagination( intval( $request->get_param( 'page' ) ), intval( $request->get_param( 'per_page' ) ) )
        );

        return Response::send(
            [
                "total"      => $count_query->count( 'id' ),
                "recipients" => $recipients
            ]
        );
    }
}