<?php
	include '../includes/overall.inc.php';

use Mnv\Core\Config;
use Mnv\Core\Feedback;
use Mnv\Core\Locale\I18N;
use Mnv\Core\Validations\Exceptions\InvalidEmailException;
use Mnv\Core\Validations\ValidateEmail;

if (request()->ajax()) {

    $class = new Feedback();

    $error    = '';
    $response  = null;
    $captchaGood = false;
    $attachment = null;

    $rewrite   = request()->get('rewrite');
    $feedback  = request()->get('feedback');
    $recaptcha_token    = request()->get('recaptcha_token');
    $g_recaptcha_response    = request()->get('g-recaptcha-response');
    $bot                = request()->get('bot');

    if (request()->hasFile('file')) {
        $attachment = request()->files->get('file');
    }

    var_dump($attachment);
    if ($rewrite != Config::getValue('rewrite')) {
        header("HTTP/1.0 301 Moved Permanently");
        header("Location: " . SITE_URL);

        exit;
    }

    if (!empty($feedback['email'])) {
        try {
            ValidateEmail::fromString($feedback['email']);
        } catch (InvalidEmailException $e) {
            $class->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
            $class->errors = 'email';
        } catch (InvalidArgumentException $e) {
            $class->message = I18N::locale("Введите E-mail корректно", "Elektron pochtani to'g'ri kiriting", "Enter the E-mail correctly");
            $class->errors = 'email';
        }
    }

//    else {
//        $class->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
//        $class->errors = 'email';
//    }

    if (empty($feedback['subject'])) {
        $feedback['subject'] = Config::getValue('smtp_subject');
    }
    $feedback['subject'] = preg_replace("/(%0A|%0D|\n|\r)/i", '', trim($feedback['subject']));

    if (!empty($feedback['fullName'])) {
        $feedback['fullName'] = preg_replace("/(%0A|%0D|\n|\r)/i", '', trim($feedback['fullName']));
        $class->checkName($feedback['fullName']);
    } else {
        $class->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
        $class->errors = 'fullName';
    }

    if (!empty($feedback['phone'])) {
        $feedback['phone'] = preg_replace("/(%0A|%0D|\n|\r)/i", '', trim($feedback['phone']));
    } else {
        $class->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
        $class->errors = 'phone';
    }

/* checking whether message is empty */
//    if (empty($feedback['message'])) $class->errors = 'message';


    $arrayMessage = array_filter([
        'Дата отправки сообщения' => adjustTime(gmdate('d-m-Y H:i'), false, 'd-m-Y H:i'),
        'Ф.И.О.'            => $feedback['fullName'],
        'Телефон'           => $feedback['phone'] ?? null,
        'Е-майл'            => $feedback['email'] ?? null,
        'Компании'          => $feedback['company'] ?? null,
        'Контактные данные' => $feedback['contact'] ?? null,
        'Сообщение'         => $feedback['message'] ?? null,
    ]);

    $htmlBody = '';
    foreach($arrayMessage as $key => $value) {
        $htmlBody .= "<b>".$key.":</b> ".$value."<br />";
    }

    if (empty($class->errors)) {
        if ($class->getCaptchaEnabled() == 1) {
            if ($class->getAllowCaptcha() == 1 &&  !empty($bot)) {
                if ($class->antiBot($bot)) {
                    $captchaGood = true;
                } else {
                    $response = array('status' => 400, 'message' => $class->message,'errors' => $class->errors,  'color' => 'red');
                }
            } elseif ($class->getAllowCaptcha() == 2) {
                if ($class->validateReCaptchaV2($g_recaptcha_response)) {
                    $captchaGood = true;
                } else {
                    $response = array('status' => 400, 'message' => $class->message, 'errors' => $class->errors, 'color' => 'red');
                }
            }
            elseif ($class->getAllowCaptcha() == 3) {
                if ($class->validateReCaptchaV3($recaptcha_token)) {
                    $captchaGood = true;
                } else {
                    $response = array('status' => 400, 'message' => $class->message,'errors' => $class->errors, 'color' => 'red');
                }
            }
        }

        /* если все good, то пропускаем на отправку */
        if (empty($class->errors) && $captchaGood) {

            $class->send_telegram('feedback_', ["#" .$feedback['subject'], $feedback]);

            /* отправка по smtp */
            if (empty($class->errors)) {
               if ($class->send($feedback['email'] ?? null, $feedback['fullName'], $feedback['subject'], $htmlBody, $attachment)) {
                   $response = array('status' => 200, 'type' => 'success', 'message' => I18N::locale("Ваше сообщение успешно отправлено", "Sizning xabaringiz muvaffaqiyatli yuborildi", "Your message has been sent successfully"));
                   $class->insertMail($feedback, $htmlBody);
                } else {
                    $response = array('status' => 400, 'message' => $class->message, 'error' => $class->errors, 'type' => 'error');
                }
            } else {
                $response = array('status' => 400, 'message' => $class->message, 'error' => $class->errors,  'type' => 'error');
            }
        }

    } else {
        $response = array('status' => 400, 'message' => $class->message, 'error' => $class->errors, 'type' => 'error');
    }

    return response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();

} else {
    die('Hacking attempt!');
}


  

