<?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()) {

    $feedbackClass = new Feedback();

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

    $rewrite   = request()->get('rewrite');
    $feedback  = request()->get('resume');
    $jobs       = request()->get('job');
    $langs      = request()->get('lang');
    $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) {
            $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';
        }
    }


    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']));
    } 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';

    $languages = '';

    if (!empty($langs)) {
        $language = [];
        $idx = 1;
        foreach ($langs as $lang) {
            $language[] = $idx . ') ' . $lang['lang'] . ': ' . $lang['level'];
            $idx++;
        }
        $languages = implode(", ", $language);
    }

    $jobImplode = '';

    if (!empty($jobs)) {
        $jobText = [];
        $index = 1;
        foreach ($jobs as $job) {
            $jobText[] = $index . ') Компании: ' . $job['company']
                . ', Профиль деятельности: ' . $job['activityProfile']
                . ', Перирод трудовой деятельности: ' . $job['employmentPeriod']
                . ', Функциональные обязанности: ' . $job['responsibilities']
                . ', Причина ухода: ' . $job['reason'];

            $index++;
        }
        $jobImplode = implode(". ", $jobText);
    }
    $arrayMessage = array_filter([
        'Дата отправки сообщения' => adjustTime(gmdate('d-m-Y H:i'), false, 'd-m-Y H:i'),
        'Ф.И.О.'                => $feedback['fullName'],
        'Дату рождения'         => $feedback['birthDate'],
        'Место рождения'        => $feedback['birthPlace'],
        'Национальность'        => $feedback['nationality'],
        'Гражданство'           => $feedback['citizenship'],
        'Место жительства'      => $feedback['residence'],
        'Семейное положение'    => $feedback['marriage'],

        'Телефон'           => $feedback['phone'] ?? null,
        'Е-майл'            => $feedback['email'] ?? null,

        // Образование
        'Образование'                               => $feedback['education'],
        'Наименования учебного заведения'           => $feedback['educationName'],
        'Дополнительное обучение'                   => $feedback['training'],
        'Навыки работы на персональном компьютере'  => $feedback['skills'],
        'Знание языков'  => $languages,
        'Трудовая деятельность'  => $jobImplode,

        // Уголовка
        'Привлекались ли Вы к административной или уголовной ответственности' => $feedback['criminal'],


        'ФИО и номер бывшего Руководителя'  => $feedback['formerHead'],


        'Сообщение' => $feedback['message'] ?? null,
    ]);

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

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

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

            $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(
                       "Ваше сообщение успешно отправлено",
                       "Сизнинг хабарингиз муваффақиятли юборилди",
                       "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!');
}


  

