<?php
session_start();

require_once './include/Constants.php';
require_once './include/Helper.php';
require_once './vendor/autoload.php';
require_once './include/DatabaseConn.php';
require_once './models/User.php';
require_once './models/Settings.php';
require_once './models/LoginRecord.php';

if (isset($_POST['register'])) {
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if ($email == null || $email == false) {
        $error = 'Email is not valid';
    } else {
        $db = new DatabaseConn();
        $link = $db->connect();
        $email = strtolower($email);
        $stmt = mysqli_prepare($link, 'select email from users WHERE  email = ?');
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $error = 'Email already exist!';
        }
    }
    if (!empty(trim($_POST['ref_email']))) {
        $ref_email = trim($_POST['ref_email']);
        if ($ref_email == null || $ref_email == false) {
            $error = 'Referral Email is not valid';
        } elseif (strcmp($ref_email, $email) == 0) {
            $error = 'Referral email should not be the same with your email. You may leave it blank';
        } else {
            $db = new DatabaseConn();
            $link = $db->connect();
            $email = strtolower($email);
            $stmt = mysqli_prepare($link, 'select email from users WHERE  email = ?');
            $stmt->bind_param('s', $ref_email);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows == 0) {
                $error = 'Referral Email does not exist. You may leave it blank';
            }
        }
    }
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    if ($name == null || ctype_alpha(preg_replace('/\s+/', '', $name)) == false) {
        $error = 'Name is not valid. Name should contain strings only';
    } elseif (strlen($name) <= 3) {
        $error = 'Name is too short';
    }
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
    if ($phone == null) {
        $error = 'Phone is not valid.';
    }
    $country = filter_input(INPUT_POST, 'country', FILTER_SANITIZE_STRING);
    if ($country == null || ctype_alpha(preg_replace('/\s+/', '', $country)) == false || strcmp($country, NONE) == 0) {
        $error = 'Please select a country';
    }
    $gender = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
    if ($gender == null || ctype_alpha(preg_replace('/\s+/', '', $gender)) == false || strcmp($gender, NONE) == 0) {
        $error = 'Please select a gender';
    }
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
    if ($password == null || $password == false) {
        $error = 'Password is not valid';
    } elseif (strlen($password) < 8) {
        $error = 'Password is weak';
    }

    // $cpassword = filter_input(INPUT_POST, 'cpassword', FILTER_SANITIZE_STRING);
    // if (strcmp($password, $cpassword) != 0) {
    //     $error = 'Password does not match';
    // }

    if (!isset($error)) {
        $db = new DatabaseConn();
        $link = $db->connect();
        $settings = Settings::getSystemSettings($link);
        date_default_timezone_set('Africa/Lagos');
        $time = time();
        $user = new User();
        $user->setCountry($country);
        $user->setDateJoined($time);
        $user->setEmail($email);
        $user->setName($name);
        $user->setPassword($password);
        $user->setPhone($phone);
        $user->setGender($gender);
        $user->setStatus($settings->getEmailVerification() == 1 ? NOT_CONFIRMED : NEW_USER);
        User::saveUser($user, $link);
        if (!empty(trim($_POST['ref_email']))) {
            $stmt = mysqli_prepare($link, 'Insert INTO referral(`user`,guest,`date`) VALUES(?,?,?)');
            $stmt->bind_param('sss', $ref_email, $email, $time);
            $stmt->execute();
        }
        $response = strcmp($user->getStatus(), NOT_CONFIRMED) == 0 ? User::sendEmailVerification($user, $link) : false;
        if ($response) {
            $_SESSION[EMAIL] = $user->getEmail();
            header('location: confirm');
            die();
        } elseif (is_null($response)) {
            $error = "We couldn't verify your email";
        } else {
            LoginRecord::saveUserRecords($user, $link);
            $_SESSION[USER] = $user->getEmail();
            header('location: dashboard/');
            die();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zxx">

<head>
    <?php require_once './partials/head.php'; ?>
    <style>
        #footer_section {
            /*  padding-top: 135px;*/
        }
    </style>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/css/intlTelInput.min.css" />

</head>

<body>
    <div class="sub-banner-section-outer position-relative">
        <header>
            <?php require_once './partials/header.php'; ?>
        </header>
        <section class="contact_info_section position-relative">
            <div class="container">
                <div class="row">
                    <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                        <div class="banner-section-content">
                            <h1 class="text-white" data-aos="fade-up">Create an Account</h1>
                            <p class="text-white" data-aos="fade-right">Already have an account? <a href="login"
                                    style="color: #e73c3e">Login</a></p>
                        </div>
                    </div>
                    <div class="col-lg-6 col-md-6 col-sm-12 col-12">
                        <div class="banner_image position-relative">
                            <div class="contact_info_form_content">
                                <form id="contactpage" style="height: 830px;" method="POST" action="register">
                                    <?php if (isset($error)) { ?>
                                    <p class="error" style="color: red">Error: <?php echo "$error"; ?></p>
                                    <?php } ?>
                                    <div class="row">
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <input type="text" id="fldFName" value="<?php
                                                if (isset($_POST['name'])) {
                                                    echo $_POST['name'];
                                                }
                                                ?>"
                                                    name="name" placeholder="Full Name" class="form-control"
                                                    required="required">
                                            </div>
                                        </div>
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <input type="tel" style="padding-right: 6px; padding-left: 52px;"
                                                    id="phone" value="<?php
                                                    if (isset($_POST['phone'])) {
                                                        echo $_POST['phone'];
                                                    }
                                                    ?>" name="phone"
                                                    placeholder="Phone" class="form-control" required="required">
                                            </div>
                                        </div>
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <select class="form-control" required
                                                    style="height: 66px; margin-bottom: 22px;/*! background-color: pink; */background-color: #20202c;color: var(--e-global-color-text);border-color: #20202c;"
                                                    id="country" name="country">
                                                    <?php require_once './include/countries.php'; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <select class="form-control" required
                                                    style="height: 66px; margin-bottom: 22px;/*! background-color: pink; */background-color: #20202c;color: var(--e-global-color-text);border-color: #20202c;"
                                                    id="gender" name="gender">
                                                     <option value="None">Select Gender</option>
                                                     <option value="male">Male</option>
                                                     <option value="female">Female</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <input type="email" value="<?php
                                                if (isset($_POST['email'])) {
                                                    echo $_POST['email'];
                                                }
                                                ?>" name="email"
                                                    placeholder="Email Address" class="form-control"
                                                    required="required">
                                            </div>
                                        </div>
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <input type="password" name="password" placeholder="Password"
                                                    class="form-control password" required="required">
                                            </div>
                                        </div>
                                        <input type="hidden" name="register" style="display: none" />
                                        <div class="col-lg-12 col-md-12 col-sm-12">
                                            <div class="form-group mb-0">
                                                <input type="email" name="ref_email"
                                                    placeholder="Referral Email (Optional)" class="form-control"
                                                    value="<?php
                                                    if (isset($_GET[REFERRAL])) {
                                                        $ref = filter_input(INPUT_GET, REFERRAL, FILTER_VALIDATE_EMAIL);
                                                        if (is_null($ref) || is_bool($ref)) {
                                                        } else {
                                                            echo "$ref";
                                                        }
                                                    } elseif (isset($_POST['ref_email'])) {
                                                        echo $_POST['ref_email'];
                                                    }
                                                    ?>">

                                            </div>
                                        </div>
                                    </div>
                                    <div class="btn_wrapper">
                                        <button type="submit" name="get_started" id="started"
                                            class="default-btn">Create Account <i
                                                class="fa-solid fa-angle-right"></i></button>
                                    </div>
                                </form>
                            </div>
                            <figure class="banner_image_bottom_shape mb-0 position-absolute top_bottom_shape">
                                <img src="images/sub_banner_image_bottom_shape.png" alt class="img-fluid">
                            </figure>
                        </div>
                    </div>
                </div>
            </div>
        </section>

    </div>

    <?php require_once './partials/footer.php'; ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/intlTelInput.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

    <script>
        (function() {
            <?php if (isset($_POST['country'])) { ?>
            var theValue = '<?php echo $_POST['country']; ?>';
            var query = 'select#country option[value="' + theValue + '"]';
            $(query).attr("selected", true);
            <?php } ?>
            $(".placeholder").select2({
                placeholder: "Make a Selection",
            });

            let select2 = $(".placeholder").select2();
            select2.data('select2').$selection.css('height', '45.4px');
            select2.data('select2').$selection.css('padding', '7px 20px');

            var input = document.querySelector("#phone");
            let iti = window.intlTelInput(input, {
                initialCountry: "US",
                geoIpLookup: function(success, failure) {
                    $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
                        var countryCode = (resp && resp.country) ? resp.country : "";
                        success(countryCode);
                    });
                },
                utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.min.js"
            });
            $('#btnreg').click(function(e) {
                e.preventDefault();
                let number = iti.getNumber();
                console.log(number);
                $('#phone').val(number);
                $('#rgForm').submit();
            });
            $(".toggle-password").click(function() {

                $(this).toggleClass("fa-eye fa-eye-slash");
                var input = $('input.password');
                if (input.attr("type") == "password") {
                    input.attr("type", "text");
                } else {
                    input.attr("type", "password");
                }
            });
            $(".toggle-password1").click(function() {

                $(this).toggleClass("fa-eye fa-eye-slash");
                var input = $('input.password1');
                if (input.attr("type") == "password") {
                    input.attr("type", "text");
                } else {
                    input.attr("type", "password");
                }
            });
        })();
    </script>
</body>

</html>
