<?php

namespace Vendtics\App\Http\Controllers;

defined( "ABSPATH" ) || exit;

use Vendtics\App\Http\Controllers\Controller;
use Vendtics\WpMVC\RequestValidator\Validator;
use Vendtics\App\Repositories\CampaignRecipientRepository;
use WP_REST_Request;

class EmailTrackerController extends Controller {
    public CampaignRecipientRepository $recipient_repository;

    public function __construct( CampaignRecipientRepository $recipient_repository ) {
        $this->recipient_repository = $recipient_repository;
    }

    /**
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function open( Validator $validator, WP_REST_Request $request ): array {
        if ( $request->has_param( 'token' ) ) {
            try {
                $payload     = vendtics_verify_jwt_token( $request->get_param( 'token' ) );
                $campaign_id = intval( $payload['campaign_id'] );
                $contact_id  = intval( $payload['contact_id'] );
                $recipient   = $this->recipient_repository->get_query_builder()->where( 'contact_id', $contact_id )->where( 'campaign_id', $campaign_id )->first();

                if ( $recipient ) {

                    $this->recipient_repository->get_query_builder()->where( 'contact_id', $contact_id )->where( 'campaign_id', $campaign_id )->update(
                        [
                            'open'      => $recipient->open + 1,
                            'opened_at' => current_time( 'mysql' )
                        ]
                    );
                }
            } catch ( \Throwable $th ) {
            }
        }

        // Set the correct headers for a PNG image.
        header( 'Content-Type: image/png' );
        header( 'Cache-Control: no-cache, no-store, must-revalidate' );
        header( 'Pragma: no-cache' );
        header( 'Expires: 0' );

        //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo base64_decode( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/wQAAwEB' . 'AHiOG9wAAAAASUVORK5CYII=' );
        exit;
    }

    /**
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function link( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                'token'        => 'required',
                'redirect_url' => 'required|url'
            ]
        );

        try {
            $payload     = vendtics_verify_jwt_token( $request->get_param( 'token' ) );
            $campaign_id = intval( $payload['campaign_id'] );
            $contact_id  = intval( $payload['contact_id'] );
            $recipient   = $this->recipient_repository->get_query_builder()->where( 'contact_id', $contact_id )->where( 'campaign_id', $campaign_id )->first();

            if ( $recipient ) {
                $this->recipient_repository->get_query_builder()->where( 'contact_id', $contact_id )->where( 'campaign_id', $campaign_id )->update(
                    [
                        'click'      => $recipient->click + 1,
                        'clicked_at' => current_time( 'mysql' )
                    ]
                );
            }
        } catch ( \Throwable $th ) {
        }

        //phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
        wp_redirect( $request->get_param( 'redirect_url' ) );
        exit;
    }
}
