<?php

declare(strict_types=1);

namespace App\Controller;

use App\Lib\Controller;
use App\Helpers\{EmailQueue, EmailValidator, Template, TextHelper, ArrayHelper};
use App\Models\{LoginHandler, Restaurant};
use App\Util\{Helper, JWTManager, OTP, Utility};

class ApiController extends Controller
{
    public $Helper;
    public function __construct()
    {
        @header('Access-Control-Allow-Origin: *');
        @header('Access-Control-Allow-Credentials: true');
        @header('Access-Control-Allow-Methods: GET, POST, DELETE');
        $this->Helper = new Helper;
    }

    public function tracker(string $param = null, ?string $action = null, ?string $_client = null)
    {
        if (empty($param)) {
            Helper::jsonResult(["status" => false, "message" => "Unauthorized access to webpage resource"]);
        }

        $emailQueue = new EmailQueue;

        if (Helper::is($param, 'string') && in_array($param, ["queue"])) {

            if ($action === 'open' && !empty($_client)) {

                $trackingLink = Helper::replaceStrings($_client, ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.svg', '.SVG', '.webp'], '');

                // Set the content type header to svg image
                @header('Content-Type: image/webp');
                readfile(URLROOT . APP['logo-dark']);

                $emailQueue->readTrackingLink($trackingLink);
                exit;
            }
        }
    }

    public function email(string $action)
    {
        if($action === 'contact-us'){

            $postData = $this->Helper->sanitize_post();
            $emailChecker = new EmailValidator;

            $firstName = Helper::capitalize($postData['first_name']);
            $lastName = Helper::capitalize($postData['last_name']);
            $email = Helper::trim($postData['email_address']);
            $phone = Helper::trim($postData['phone_number']);
            $message = Helper::trim($postData['message']);

            if(empty($firstName) || empty($lastName)){
                return ['status'=> false, 'message' => 'Please provide your first and last name.'];
            }

            if(empty($phone)){
                return ['status'=> false, 'message' => 'Please provide your phone number.'];
            }

            if(empty($email)){
                return ['status'=> false, 'message' => 'Please provide your email address.'];
            }

            if(!$emailChecker->isValidFormat($email)){
                return ['status'=> false, 'message' => 'Please provide a valid email address.'];
            }

            if($emailChecker->isDisposable($email)){
                return ['status'=> false, 'message' => 'Use a valid email address instead of what appears to be a disposable email address'];
            }

            if (!$emailChecker->domainExists($email)) {
                return ['status'=> false, 'message' => 'This email address appears to be a forgery.'];
            }

            if(empty($message)){
                return ['status'=> false, 'message' => 'Please provide your message.'];
            }

            $template = new Template;
            $emailQueue = new EmailQueue;
            $textHelper = new TextHelper;

            $clientTemplate = $template->email('contact-us-response');
            $adminTemplate = $template->email('contact-us-admin');

            if (!empty($clientTemplate) && !empty($adminTemplate)) {
                $clientSubject = "Thank You for Contacting Us - " . APP['name'];
                $randomReference = \mt_rand(10000000, 99999999);
                $adminSubject = "Contact Us Form Submission (#{$randomReference}) | " . APP['name'];

                $clientBody = $textHelper::replaceText($clientTemplate,
                    array_merge(array(
                    "[subject]" => $clientSubject,
                    "[person_name]" => $firstName,
                ), \MAIL_TEXT));

                $adminBody = $textHelper::replaceText($adminTemplate,
                    array_merge(array(
                    "[subject]" => $adminSubject,
                    "[customer_email]" => $email,
                    "[customer_first_name]" => $firstName,
                    "[customer_last_name]" => $lastName,
                    "[customer_phone]" => $phone,
                    "[customer_message]" => $message,
                ), MAIL_TEXT));

                $emailSender = ['email' => SMTP['email'], 'name' => SMTP['name']];

                $clientReceiver = ['email' => $email, 'name' => "{$firstName} {$lastName}"];
                $adminReceiver = ['email' => APP['email'], 'name' => APP['name']];

                $clientQueueId = $emailQueue->addQueue($emailSender, $clientReceiver, $clientSubject, $clientBody);
                $adminQueueId = $emailQueue->addQueue($emailSender, $adminReceiver, $adminSubject, $adminBody);

                return ['status' => true, 'message' => 'Thank you for contacting us, we will get back to you shortly.'];
            }
        }
    }

    public function auth(string $user, string $action)
    {
        if(empty($action) || empty($user)){
            @header("HTTP/1.1 401 Unauthorized");
            Helper::jsonResult(["status" => false, "message" => "Unauthorized access detected."]);
        }

        $postData = $this->Helper->decodePostData();

        if($action === 'refresh'){
            $bearerToken = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
            $serverToken = str_replace('Bearer ', '', $bearerToken);

            $jwtManager = new JWTManager;
            $newToken = $jwtManager->refreshToken($serverToken);

            if($newToken){
                Helper::jsonResult(['status' => true, 'message' => 'Your token has been refreshed.', 'token' => $newToken]);
            }

            @header("HTTP/1.1 401 Unauthorized");
            Helper::jsonResult(['status' => false, 'message' => 'Unauthorized access detected.']);
        }

        if($action === 'login'){

            if(empty($postData)){
                @header("HTTP/1.1 400 Bad Request");
                Helper::jsonResult(["status" => false, "message" => "Please provide your login details."]);
            }

            $deviceType = Helper::trim($postData['deviceType']);
            $loginType = Helper::trim($postData['loginType']);

            $clientEmail = Helper::trim($postData['clientEmail']);
            $clientAvatar = Helper::trim($postData['clientAvatar']);
            $clientFullName = Helper::trim($postData['clientFullName']);

            if(empty($deviceType)){
                Helper::jsonResult(["status" => false, "message" => "Please provide your device type either web or mobile."]);
            }

            if(!\in_array($deviceType, ['web', 'mobile'])){
                Helper::jsonResult(["status" => false, "message" => "Sorry, your device type is not supported."]);
            }

            if(empty($loginType)){
                Helper::jsonResult(["status" => false, "message" => "Please provide your login type either google or facebook."]);
            }

            if(!\in_array($loginType, ['google', 'facebook'])){
                Helper::jsonResult(["status" => false, "message" => "Sorry, your login type is not supported."]);
            }

            if(empty($clientEmail)){
                Helper::jsonResult(["status" => false, "message" => "Please provide your email address."]);
            }

            $loginHandler = new LoginHandler;
            $response = $loginHandler->restaurantMobileLogin($clientEmail, $clientAvatar, $clientFullName);
            Helper::jsonResult($response);
        }

        @header("HTTP/1.1 401 Unauthorized");
        Helper::jsonResult(['status' => false, 'message' => 'Sorry, no action was provided.']);
    }

    public function restaurant(string $action)
    {
        $restaurant = new Restaurant;

        if($action === 'setup_wizard'){
        }
    }

    // public function clientAuthentication(string $action)
    // {
    //     if(empty($action)){
    //         @header("HTTP/1.1 401 Unauthorized");
    //         Helper::jsonResult(["status" => false, "message" => "Unauthorized access detected."]);
    //     }

    //     $postData = $this->Helper->sanitize_post();
    //     if($action === 'forget_password'){
    //         $loginHandler = new LoginHandler;
    //         $response = $loginHandler->forgetPassword($postData['email']);
    //     }

    //     if($action === 'reset_password'){
    //         $loginHandler = new LoginHandler;
    //         $response = $loginHandler->resetPassword($postData);
    //     }

    //     if($action == 'login'){
    //         $loginHandler = new LoginHandler;
    //         $response = $loginHandler->loginClient($postData['userEmail'], $postData['userPassword']);
    //     }

    //     Helper::jsonResult($response);
    // }
}
