<?php

namespace Vendtics\App\Http\Controllers\Admin;

use Vendtics\App\Mail\Test;
use Vendtics\App\Models\Contact;

defined( "ABSPATH" ) || exit;

use Vendtics\App\Http\Controllers\Controller;
use Vendtics\WpMVC\Exceptions\Exception;
use Vendtics\WpMVC\Routing\Response;
use Vendtics\WpMVC\RequestValidator\Validator;
use Vendtics\WpMVC\View\View;
use WP_REST_Request;

class EmailController extends Controller {
    /**
     * @param Validator $validator Instance of the Validator.
     * @param WP_REST_Request $request The REST request instance.
     * @return array
     */
    public function send_test_email( Validator $validator, WP_REST_Request $request ): array {
        $validator->validate(
            [
                'to'      => 'required|string|email',
                'subject' => 'required|string|max:255',
                'body'    => 'required|string'
            ]
        );

        $contact = Contact::query()->first();
        $subject = vendtics_bind_dynamic_values( $request->get_param( 'subject' ), $contact );
        $body    = vendtics_bind_dynamic_values( $request->get_param( 'body' ), $contact );

        $mailer = new Test();
        $mailer->set_to( $request->get_param( 'to' ) )->set_subject( $subject )->set_body( View::get( 'classic-email', ['body' => $body] ) );

        if ( $mailer->send() ) {
            return Response::send(
                [
                    'message' => esc_html__( 'The email was sent successfully', 'vendtics' )
                ]
            );
        }

        return Response::send(
            [
                'message' => esc_html__( 'Failed to send email, please check your email configuration.', 'vendtics' )
            ] 
        );
    }
}