<?php 
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

    $response           = [];
    if($_SERVER["REQUEST_METHOD"] == "POST") {
        if(isset($_POST["firstname"]) && !empty($_POST["firstname"]) && isset($_POST["lastname"]) && !empty($_POST["lastname"]) && isset($_POST["email"]) && !empty($_POST["email"]) && isset($_POST["password"]) && !empty($_POST["password"]) && isset($_POST["user_agreement"]) && !empty($_POST["user_agreement"]) && isset($_POST["promotion_approval"]) && !empty($_POST["promotion_approval"]) && isset($_POST["kvkk_approval"]) && !empty($_POST["kvkk_approval"])) {
            $firstname           = trim(strip_tags($_POST["firstname"]));
            $lastname            = trim(strip_tags($_POST["lastname"]));
            $email               = trim(strip_tags($_POST["email"]));
            $password            = trim(strip_tags($_POST["password"]));
            $user_agreement      = isset($_POST["user_agreement"]) ? 1 : 0;
            $kvkk_approval       = isset($_POST["kvkk_approval"]) ? 1 : 0;
            $promotion_approval  = isset($_POST["promotion_approval"]) ? 1 : 0;

            /*if(empty($response) && !checkdnsrr(substr($email, strpos($email, '@') + 1), 'MX')) {
                $response = array('status'=>false, 'message'=>'Geçersiz e-posta adresi. Böyle bir e-posta bulunamadı.');
            }*/
            if(empty($response) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $response = array('status'=>false, 'message'=>'Hatalı e-posta adresi. Lütfen geçerli bir e-posta giriniz.');
            } 

            if(empty($response) && !isset($_POST['password']) || strlen($_POST['password']) < 6) {
                $response[] = array('status'=>false, 'element'=>'password', 'message'=>'Parolanız en az 6 karakter içermelidir.');
            }
            
            if(empty($response)) {
                if(isset($_POST['csrf_token']) && $anticsrf->validate($_POST['csrf_token'])) {
                    if($user->isUserExists($email)){
                        $response[] = array('status'=>false, 'message'=>'Bu e-postaya sahip bir hesap zaten var.');
                    }else{
                        $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                        $avatar = $utils->strtolower_tr(mb_substr($firstname, 0, 1, 'UTF-8'));
                        $avatar .= ".jpg";

                        $guid = $utils->generateGuid();
    
                        $stmt = $db->query("INSERT INTO {$db->prefix}users (`status`, `type`, `firstname`, `lastname`, `email`, `password`, `avatar`, promotion_approval, user_agreement, kvkk_approval, `guid`, `date_added`) VALUES (1, 1, :firstname, :lastname, :email, :password, :avatar, :promotion_approval, :user_agreement, :kvkk_approval, :guid, NOW())", array(':firstname'=>$firstname, ':lastname'=>$lastname, ':email'=>$email, ':password'=>$hashed_password, ':avatar'=>$avatar, ':promotion_approval'=>$promotion_approval, ':user_agreement'=>$user_agreement, ':kvkk_approval'=>$kvkk_approval, ':guid'=>$guid));
                        
                        if($stmt->error) {
                            $message = $stmt->error;
                            $utils->errorLog("error", $message, 0, $_SERVER["REQUEST_URI"]);
                            $response[] = array('status'=>false, 'message'=>'Bir hata oluştu ve isteğiniz yerine getirilemedi. Lütfen daha sonra tekrar deneyiniz.');
                        }else{
                            $email_template = file_get_contents(DIR_COMMON.'/email/templates/welcome.html');
                            $email_template = str_replace('%base_url%', $config->get('site_url'), $email_template);
                            $email_template = str_replace('%name%', $firstname." ".$lastname, $email_template);

                            $emailController	 = new EmailController($config);
                            $emailController->send(
                                array(
                                    'to'                 => array(array('email'=>$email, 'name'=>$firstname." ".$lastname)),
                                    'is_html'            => true,
                                    'subject'            => 'Ev Bazaar\'a hoşgeldiniz',
                                    'body'               => $email_template
                                )
                            );
                            $response[] = array('status'=>true, 'message'=>'Hesabınız başarıyla oluşturuldu.');
                        }
                    }
                }else {
                    $response[] = array('status'=>false, 'message'=>'Hatalı CSRF Token.');
                }
            }
        }else{
            $response = array('status'=>false, 'message'=>"Lütfen tüm zorunlu alanları doldurunuz!");
        }
    }else{
        $response = array('status'=>false, 'message'=>"Hatalı İstek!");
    }

    echo json_encode($response);