<?php 
namespace Modules\Cart\Controllers\Services;

use Modules\Cart\Providers\VerifyEmailException;
use Modules\Cart\Providers\VerifyEmailProvider;
use Symfony\Component\HttpFoundation\Request;

class VerifyEmailService
{
    /**
     * 
     */
    public function verifyEmail(Request $request)
    {
        $response = [
            'status'=> 'fail'
        ];
        $enableVerify = config('cart::sa.verify_email', false);
        if ($request->has('email') && $enableVerify) {
            $email = $request->get('email');
            $isExists = false;
            $ignoreDomain = $this->ignoreVerifyDomain($email);
            if ($email == 'sandbox@megaads.vn') {
                $ignoreDomain = true;
            }
            if (!$ignoreDomain) {
                $emailVerifier = new VerifyEmailProvider;
        
                $emailVerifier->setStreamTimeout(3);
        
                $emailVerifier->Debug = FALSE;
        
                $emailVerifier->setEmailFrom('bachnx2303@gmail.com');
        
                // Check if email is valid and exist
                if($emailVerifier->check($email)){ 
                    $response = [
                        'status' => 'successful',
                        'data' => true
                    ];
                    $isExists = true;
                } else {
                    $response['message'] = __('Unavailable email address. Please, check again!');
                }
            } else {
                $response = [
                    'status' => 'successful',
                    'data' => true
                ];
                $isExists = true;
            }
            if ($ignoreDomain || (!$ignoreDomain && $isExists)) {
                $similarDomain = $this->similarEmailPopularDomain($email);
                if ($similarDomain['status']) {
                    $replaceEmail = $similarDomain['emailName'] . '@' . $similarDomain['domain'];
                    $response['status'] = 'fail';
                    $response['percent'] = $similarDomain['percentage'];
                    $response['real'] = $replaceEmail;
                    $strMessage = __("{email}, It's your email address? {yes} {no}");
                    $emailAddress = '<span class="real-email-address">' . $replaceEmail . '</span>';
                    $confirmYes = '<span class="js-confirm-yes confirm-email">' . __('Yes') . '</span>';
                    $confirmNo = '<span class="js-confirm-no confirm-email">' . __('No') . '</span>';
                    $strMessage = str_replace('{email}', $emailAddress, $strMessage);
                    $strMessage = str_replace('{yes}', $confirmYes, $strMessage);
                    $strMessage = str_replace('{no}', $confirmNo, $strMessage);
                    $response['message'] = $strMessage;
                }
            }
        }
        return response()->json($response);
    }

    /**
     * 
     * @param string email
     * 
     * @return array retval
     */
    protected function similarEmailPopularDomain($email)
    {
        $retval = [
            'status' => false,
            'domain' => '',
            'emailName' => ''
        ];
        $splitEmail = explode('@', $email);
        $domain = $splitEmail[1];
        $popularDomain = config('sa.popularDomain', []);
        if (count($popularDomain) <= 0) {
            $popularDomain = [
                'hotmail.com',
                'outlook.com',
                'gmail.com',
                'yahoo.com'
            ];
        }
        foreach ($popularDomain as $popular) {
            similar_text($popular, $domain, $percentage);
            $percentage = ceil($percentage);
            if ($percentage >= 85 && $percentage < 100) {
                $retval = [
                    'status' => true,
                    'domain' => $popular,
                    'emailName' => $splitEmail[0], 
                    'percentage' => $percentage
                ];
                break;
            }
        }
        return $retval;
    }

    /**
     * 
     * @param string email
     * 
     * @return boolean retval
     */
    protected function ignoreVerifyDomain($email)
    {
        $retval = false;
        $splitEmail = explode('@', $email);
        $domain = $splitEmail[1];
        $ingoreDomain = config('sa.ingoreMailDomain', []);
        if (count($ingoreDomain) <= 0) {
            $ingoreDomain = [
                'outlook.com',
                'hotmail.com'
            ];
        }
        if (in_array($domain, $ingoreDomain)) {
            $retval = true;
        }
        return $retval;
    }

    /**
     * @param string message
     * 
     * @return null
     */
    protected function writeLog($messge)
    {   
        $filePath = public_path('/modules/cart/');
        if (!file_exists($filePath)) 
        {
            // create directory/folder uploads.
            mkdir($filePath, 0777, true);
        }
        $logData = $filePath . '/email_verifier_' . date('d-M-Y') . '.csv';
        // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
        file_put_contents($logData, $messge . "\n", FILE_APPEND);   
    }
}