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

use Mnv\Core\Bot\Exceptions\InvalidChatIdException;
use Mnv\Core\Bot\Exceptions\InvalidTokenException;
use Mnv\Core\Bot\Telegram;
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()) {

    $feedbackClass = new Feedback();
    $feedbackClass->getCaptchaEnabled(Config::getValue('feedback_captcha_enabled'));
    $feedbackClass->getAllowCaptcha(Config::getValue('allow_recaptcha'));

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

    $rewrite   = request()->get('rewrite');
    $feedback  = request()->get('feedback');
    $bot       = request()->get('bot');

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

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

        exit;
    }

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

//    else {
//        $feedbackClass->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
//        $feedbackClass->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']));
        $feedbackClass->checkName($feedback['fullName']);
    } else {
        $feedbackClass->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
        $feedbackClass->errors = 'fullName';
    }

    if (!empty($feedback['phone'])) {
        $feedback['phone'] = preg_replace("/(%0A|%0D|\n|\r)/i", '', trim($feedback['phone']));
        try {
            \Mnv\Core\Validations\ValidatePhone::fromString($feedback['phone']);
        } catch (\Mnv\Core\Validations\Exceptions\InvalidPhoneException $e) {
            $feedbackClass->message = I18N::locale("Введите номер телефона корректно", "Telefon raqamini to'g'ri kiriting", "Enter the phone number correctly");
            $feedbackClass->errors = 'phone';
        }
    } else {
        $feedbackClass->message = I18N::locale("Поле не должно быть пустым", "Maydon bo'sh bo'lmasligi kerak", "The field should not be empty");
        $feedbackClass->errors = 'phone';
    }

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


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

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

    if (empty($feedbackClass->errors)) {

        /* проверка включена капча */
        if ($feedbackClass->setCaptchaEnabled() == 1) {

            /* вид капчи */
            if ($feedbackClass->setAllowCaptcha() == 1) {
                if (empty($feedbackClass->errors) && $feedbackClass->captchaToken($_POST['token'])) {
                    $captchaGood = true;
                } else {
                    $response = array('status' => 400, 'message' => $feedbackClass->message, 'error' => $feedbackClass->errors, 'type' => 'error');
                }
            } else {
                if (empty($feedbackClass->errors) && $feedbackClass->antiBot($bot['anti-bot-a'], $bot['anti-bot-q'], $bot['anti-email'])) {
                    $captchaGood = true;
                } else {
                    $response = array('status' => 400, 'message' => $feedbackClass->message, 'error' => $feedbackClass->errors, 'type' => 'error');
                }
            }

        }

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

            $feedbackClass->send_telegram('feedback_', ["#" .$feedback['subject'], $feedback]);
            
            /* отправка по smtp */
            if (empty($feedbackClass->errors)) {
               if ($feedbackClass->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"));
                    $feedbackClass->insertMail($feedback, $htmlBody);
                } else {
                    $response = array('status' => 400, 'message' => $feedbackClass->message, 'error' => $feedbackClass->errors, 'type' => 'error');
                }
            } else {
                $response = array('status' => 400, 'message' => $feedbackClass->message, 'error' => $feedbackClass->errors,  'type' => 'error');
            }
        }

    } else {
        $response = array('status' => 400, 'message' => $feedbackClass->message, 'error' => $feedbackClass->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!');
}


  

