<?php

namespace Vendtics\App\Services;

defined( 'ABSPATH' ) || exit;

use Vendtics\App\Repositories\ContactRepository;
use Vendtics\App\Repositories\SettingsRepository;
use Exception;

class DoubleOptIn {
    public ContactRepository $contact_repository;

    public SettingsRepository $settings_repository;

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

    /**
     * Triggers the double opt-in process for a given contact.
     *
     * This method retrieves the contact information, validates the contact's eligibility
     * for the double opt-in process based on the settings, and sends a double opt-in email
     * if the conditions are met.
     *
     * @param int|\stdClass $contact Contact ID or contact object.
     * @param bool          $force   Whether to force the double opt-in process regardless of contact status.
     *
     * @throws \Exception If the contact ID is provided but the contact cannot be found.
     *
     * @return bool True if the double opt-in email was sent successfully, false otherwise.
     */
    public function trigger( $contact, bool $force = false ) {
        if ( is_int( $contact ) ) {
            $contact = $this->contact_repository->get_by_id( $contact );

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

        $optin_settings = $this->settings_repository->get_settings()['double_optin'];

        if ( ! $optin_settings['status'] ) {
            return false;
        }

        if ( ! $force && "pending" !== $contact->status ) {
            return false;
        }

        $body = vendtics_bind_dynamic_values( $optin_settings['email_body'], $contact );

        $double_mailer = new \Vendtics\App\Mail\DoubleOptIn;
        $double_mailer->set_to( $contact->email )->set_subject( $optin_settings['email_subject'] )->set_body( $body );

        return $double_mailer->send( $contact, $optin_settings );
    }
}