<?php
session_start();
require_once '../models/User.php';
require_once '../include/DatabaseConn.php';
require_once '../include/Constants.php';
require_once '../models/Admin.php';

$admin = Admin::getCurrentAdmin();

if (is_null($admin)) {
    $url = $_SERVER['REQUEST_URI'];
    header("location: ./login?" . RETURN_URL . "=" . $url);
    die();
}

$db = new DatabaseConn();
$link = $db->connect();

if (isset($_POST['email'])) {
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if ($email == null || $email == FALSE) {
        $error = 'Email is not valid';
    } else {
        $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'])) && strcmp(NONE, trim($_POST['ref_email'])) != 0) {
        $ref_email = trim($_POST['ref_email']);
        if ($ref_email == null || $ref_email == FALSE) {
            $error = 'Referral Email is not valid';
        } else if (strcmp($ref_email, $email) == 0) {
            $error = "Referral is you. Please leave it blank";
        } else {
            $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 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';
    } else if (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 (empty($country) || $country == null || ctype_alpha(preg_replace('/\s+/', '', $country)) == FALSE || strcmp($country, NONE) == 0) {
        $error = 'Please select a country';
    }
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
    if ($password == null || $password == FALSE) {
        $error = 'Password is not valid';
    }
    if (!isset($error)) {
        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->setStatus(NEW_USER);
        $response = User::saveUser($user, $link);
        if ($response) {
            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();
            }
        } else {
            $error = "Something went wrong. Contact the developer";
        }
        $_SESSION[SUCCESS] = "User successfully added!";
        header("location: index");
    }
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?php require_once './partials/head.php'; ?>
        <style>
            :focus{outline:0}.select2.select2-container.form-control-sm{padding:7px 24px;font-size:13px;height:auto}.select2-container-default .select2-selection-single .select2-selection__arrow{height:26px;position:absolute;top:14px;right:29px;width:20px}.select2-container--default.form-control-sm .select2-selection--single .select2-selection__arrow{height:6px;position:absolute;top:17px;right:31px;width:20px}.select2-container{box-sizing:border-box;display:inline-block;margin:0;position:relative;vertical-align:middle;width:100%!important}.select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;width:100%;user-select:none;-webkit-user-select:none}.select2-container--default.select2-container--open .select2-selection--multiple,span.select2.select2-container.select2-container--default.select2-container--open .select2-selection--single{border:1px solid #1b55e2;box-shadow:0 0 5px 2px rgba(194,213,255,.6196078431372549)}.select2-container .select2-selection--single .select2-selection__rendered{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:1px solid #bfc9d4;color:#3b3f5c!important;font-size:15px;padding:8px 10px;letter-spacing:1px;background-color:#fff;height:calc(1.4em + 1.4rem + 2px);padding:.75rem 1.25rem;border-radius:6px;box-shadow:none}.select2-container .select2-selection--single .select2-selection__clear{position:relative}.select2-container[dir=rtl] .select2-selection--single .select2-selection__rendered{padding-right:8px;padding-left:20px}.select2-container .select2-selection--multiple{box-sizing:border-box;cursor:pointer;display:block;min-height:32px;user-select:none;-webkit-user-select:none}.select2-container .select2-selection--multiple .select2-selection__rendered{display:inline-block;overflow:hidden;padding-left:8px;text-overflow:ellipsis;white-space:nowrap}.select2-container .select2-search--inline{float:left}.select2-container .select2-search--inline .select2-search__field{box-sizing:border-box;border:none;font-size:100%;margin-top:5px;padding:0}.select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none}.select2-dropdown{background-color:#fff;border:1px solid #ebedf2;border-radius:4px;box-sizing:border-box;display:block;position:absolute;left:-100000px;width:100%;z-index:950;-webkit-box-shadow:2px 5px 17px 0 rgba(31,45,61,.1);box-shadow:2px 5px 17px 0 rgba(31,45,61,.1)}.select2-results{display:block}.select2-results__options{list-style:none;margin:0;padding:0}.select2-results__option{padding:13px 19px;user-select:none;-webkit-user-select:none}.select2-results__option[aria-selected]{cursor:pointer;color:#888ea8;font-weight:600}.select2-container--open .select2-dropdown{left:0}.select2-container--open .select2-dropdown--above{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--open .select2-dropdown--below{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.select2-search--dropdown{display:block;padding:4px}.select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box}.select2-search--dropdown .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none}.select2-search--dropdown.select2-search--hide{display:none}.select2-close-mask{border:0;margin:0;padding:0;display:block;position:fixed;left:0;top:0;min-height:100%;min-width:100%;height:auto;width:auto;opacity:0;z-index:99;background-color:#fff}.select2-hidden-accessible{border:0!important;clip:rect(0 0 0 0)!important;-webkit-clip-path:inset(50%)!important;clip-path:inset(50%)!important;height:1px!important;overflow:hidden!important;padding:0!important;position:absolute!important;width:1px!important;white-space:nowrap!important}.select2-container--default .select2-selection--single{background-color:#fff;border-radius:4px}.select2-container--default .select2-selection--single .select2-selection__rendered{color:#3b3f5c;border-radius:4px}.select2-container--default .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:700;margin-right:5px}.select2-container--default .select2-selection--single .select2-selection__placeholder{color:#888ea8}.select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:10px;right:7px;width:20px}.select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}.select2-container--default[dir=rtl] .select2-selection--single .select2-selection__clear{float:left}.select2-container--default[dir=rtl] .select2-selection--single .select2-selection__arrow{left:1px;right:auto}.select2-container--default.select2-container--disabled .select2-selection--single{background-color:#eee;cursor:default}.select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear{display:none}.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px}.select2-container--default .select2-selection--multiple{background-color:#fff;border-radius:4px;cursor:text;border:1px solid #bfc9d4;color:#3b3f5c;font-size:15px;padding:8px 16px;letter-spacing:1px;font-weight:700;background:#f1f2f3}.select2-container--default .select2-selection--multiple .select2-selection__rendered{box-sizing:border-box;list-style:none;margin:0;padding:0 5px;width:100%}.select2-container--default .select2-selection--multiple .select2-selection__rendered li{list-style:none;width:auto}.select2-container--default .select2-selection--multiple .select2-selection__placeholder{color:#888ea8;margin-top:5px;float:left}.select2-container--default .select2-selection--multiple .select2-selection__clear{cursor:pointer;float:right;font-weight:700;margin-top:5px;margin-right:10px}.select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #ebedf2;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove{color:#888ea8;cursor:pointer;display:inline-block;font-weight:700;margin-right:2px}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover{color:#0e1726}.select2-container--default[dir=rtl] .select2-selection--multiple .select2-search--inline,.select2-container--default[dir=rtl] .select2-selection--multiple .select2-selection__choice,.select2-container--default[dir=rtl] .select2-selection--multiple .select2-selection__placeholder{float:right}.select2-container--default[dir=rtl] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto}.select2-container--default[dir=rtl] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto}.select2-container--default.select2-container--focus .select2-selection--multiple{outline:0}.select2-container--default.select2-container--disabled .select2-selection--multiple{background-color:#eee;cursor:default}.select2-container--default.select2-container--disabled .select2-selection__choice__remove{display:none}.select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple,.select2-container--default.select2-container--open.select2-container--above .select2-selection--single{border-top-left-radius:0;border-top-right-radius:0}.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple,.select2-container--default.select2-container--open.select2-container--below .select2-selection--single{border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--default .select2-search--dropdown .select2-search__field{border:1px solid #515365;color:#3b3f5c;font-size:15px;padding:12px 16px;letter-spacing:1px;font-weight:700;border-radius:4px}.select2-container--default .select2-search--inline .select2-search__field{background:0 0;border:none;outline:0;box-shadow:none;-webkit-appearance:textfield;width:100%!important}.select2-container--default .select2-results>.select2-results__options{max-height:200px;overflow-y:auto}.select2-container--default .select2-results__option[role=group]{padding:0}.select2-container--default .select2-results__option[aria-disabled=true]{color:#888ea8}.select2-container--default .select2-results__option[aria-selected=true]{background-color:rgba(27,85,226,.23921568627450981);color:#1b55e2}.select2-container--default .select2-results__option .select2-results__option{padding-left:1em}.select2-container--default .select2-results__option .select2-results__option .select2-results__group{padding-left:0}.select2-container--default .select2-results__option .select2-results__option .select2-results__option{margin-left:-1em;padding-left:2em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-2em;padding-left:3em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-3em;padding-left:4em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-4em;padding-left:5em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-5em;padding-left:6em}.select2-container--default .select2-results__option--highlighted[aria-selected]{color:#1b55e2}.select2-container--default .select2-results__group{cursor:default;display:block;padding:13px 14px;font-weight:700;color:#3b3f5c}.select2-container--classic .select2-selection--single{background-color:#f1f2f3;border:1px solid #ebedf2;border-radius:4px;outline:0;background-image:-webkit-linear-gradient(top,#fff 50%,#eee 100%);background-image:-o-linear-gradient(top,#fff 50%,#eee 100%);background-image:linear-gradient(to bottom,#fff 50%,#eee 100%);background-repeat:repeat-x}.select2-container--classic .select2-selection--single:focus{border:1px solid #5897fb}.select2-container--classic .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px}.select2-container--classic .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:700;margin-right:10px}.select2-container--classic .select2-selection--single .select2-selection__placeholder{color:#888ea8}.select2-container--classic .select2-selection--single .select2-selection__arrow{background-color:#ddd;border:none;border-left:1px solid #ebedf2;border-top-right-radius:4px;border-bottom-right-radius:4px;height:26px;position:absolute;top:1px;right:1px;width:20px;background-image:-webkit-linear-gradient(top,#eee 50%,#ccc 100%);background-image:-o-linear-gradient(top,#eee 50%,#ccc 100%);background-image:linear-gradient(to bottom,#eee 50%,#ccc 100%);background-repeat:repeat-x}.select2-container--classic .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}.select2-container--classic[dir=rtl] .select2-selection--single .select2-selection__clear{float:left}.select2-container--classic[dir=rtl] .select2-selection--single .select2-selection__arrow{border:none;border-right:1px solid #ebedf2;border-radius:0;border-top-left-radius:4px;border-bottom-left-radius:4px;left:1px;right:auto}.select2-container--classic.select2-container--open .select2-selection--single{border:1px solid #5897fb}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow{background:0 0;border:none}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single{border-top:none;border-top-left-radius:0;border-top-right-radius:0;background-image:-webkit-linear-gradient(top,#fff 0,#eee 50%);background-image:-o-linear-gradient(top,#fff 0,#eee 50%);background-image:linear-gradient(to bottom,#fff 0,#eee 50%);background-repeat:repeat-x}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;background-image:-webkit-linear-gradient(top,#eee 50%,#fff 100%);background-image:-o-linear-gradient(top,#eee 50%,#fff 100%);background-image:linear-gradient(to bottom,#eee 50%,#fff 100%);background-repeat:repeat-x}.select2-container--classic .select2-selection--multiple{background-color:#fff;border:1px solid #ebedf2;border-radius:4px;cursor:text;outline:0}.select2-container--classic .select2-selection--multiple:focus{border:1px solid #5897fb}.select2-container--classic .select2-selection--multiple .select2-selection__rendered{list-style:none;margin:0;padding:0 5px}.select2-container--classic .select2-selection--multiple .select2-selection__clear{display:none}.select2-container--classic .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove{color:#888;cursor:pointer;display:inline-block;font-weight:700;margin-right:2px}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover{color:#555}.select2-container--classic[dir=rtl] .select2-selection--multiple .select2-selection__choice{float:right;margin-left:5px;margin-right:auto}.select2-container--classic[dir=rtl] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto}.select2-container--classic.select2-container--open .select2-selection--multiple{border:1px solid #5897fb}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--classic .select2-search--dropdown .select2-search__field{border:1px solid #aaa;outline:0}.select2-container--classic .select2-search--inline .select2-search__field{outline:0;box-shadow:none}.select2-container--classic .select2-dropdown{background-color:#fff;border:1px solid transparent}.select2-container--classic .select2-dropdown--above{border-bottom:none}.select2-container--classic .select2-dropdown--below{border-top:none}.select2-container--classic .select2-results>.select2-results__options{max-height:200px;overflow-y:auto}.select2-container--classic .select2-results__option[role=group]{padding:0}.select2-container--classic .select2-results__option[aria-disabled=true]{color:grey}.select2-container--classic .select2-results__option--highlighted[aria-selected]{background-color:#3875d7;color:#fff}.select2-container--classic .select2-results__group{cursor:default;display:block;padding:6px}.select2-container--classic.select2-container--open .select2-dropdown{border-color:#5897fb}
        </style>
    </head>
    <body>
        <div id="app">
            <?php require_once './partials/top-header.php'; ?>
            <!--  BEGIN MAIN CONTAINER  -->
            <div class="main-container" id="container">
                <div class="overlay"></div>
                <div class="search-overlay"></div>
                <?php require_once './partials/side-bar.php'; ?>
                <!--  BEGIN CONTENT AREA  -->
                <div id="content" class="main-content">
                    <div class="layout-px-spacing">
                        <div class="row layout-top-spacing layout-spacing">
                            <div class="col-lg-11 offset-lg-1">
                                <div class="statbox widget box box-shadow">
                                    <div class="widget-content widget-content-area">
                                        <form method="post" action="add-new-user">
                                            <?php if (isset($error)) { ?>
                                                <div class="alert alert-danger mb-4" role="alert">
                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                        <svg
                                                            xmlns="http://www.w3.org/2000/svg"
                                                            width="24"
                                                            height="24"
                                                            viewBox="0 0 24 24"
                                                            fill="none"
                                                            stroke="currentColor"
                                                            stroke-width="2"
                                                            stroke-linecap="round"
                                                            stroke-linejoin="round"
                                                            class="feather feather-x close"
                                                            data-dismiss="alert"
                                                            >
                                                        <line x1="18" y1="6" x2="6" y2="18"></line>
                                                        <line x1="6" y1="6" x2="18" y2="18"></line>
                                                        </svg>
                                                    </button>
                                                    <strong>Error!</strong> <?php echo "$error"; ?>
                                                </div>
                                            <?php } ?>
                                            <div class="form-group row mb-4">
                                                <label for="hEmail" class="col-xl-2 col-sm-3 col-sm-2 col-form-label">Select Referral (Optional)</label>
                                                <div class="col-xl-10 col-lg-9 col-sm-10">
                                                    <select class="placeholder js-states form-control" name="ref_email">
                                                        <option selected value="<?php echo NONE; ?>">None</option>
                                                        <?php
                                                        $users = User::getUsers($link);
                                                        if (!is_null($users)) {
                                                            foreach ($users as $user) {
                                                                if (count($users)) {
                                                                    ?>
                                                                    <option value="<?php echo "{$user->getEmail()}"; ?>"><?php echo "{$user->getName()}"; ?></option>
                                                                    <?php
                                                                }
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-group row mb-4">
                                                <label  class="col-xl-2 col-sm-3 col-sm-2 col-form-label">Full Name</label>
                                                <div class="col-xl-10 col-lg-9 col-sm-10">
                                                    <input type="text" class="form-control" value="<?php
                                                    if (isset($_POST['name'])) {
                                                        echo ($_POST['name']);
                                                    }
                                                    ?>" name="name" placeholder="" required>
                                                </div>
                                            </div>
                                            <div class="form-group row mb-4">
                                                <label for="hPassword" class="col-xl-2 col-sm-3 col-sm-2 col-form-label">Country</label>
                                                <div class="col-xl-10 col-lg-9 col-sm-10">
                                                    <select class="placeholder js-states form-control" required id="country" name="country">
                                                        <?php include_once '../include/countries.php'; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-group row mb-4">
                                                <label class="col-xl-2 col-sm-3 col-sm-2 col-form-label">Email</label>
                                                <div class="col-xl-10 col-lg-9 col-sm-10">
                                                    <input type="email" value="<?php
                                                    if (isset($_POST['email'])) {
                                                        echo ($_POST['email']);
                                                    }
                                                    ?>" class="form-control" required name="email" placeholder="">
                                                </div>
                                            </div>
                                            <div class="form-group row mb-4">
                                                <label for="hPassword" class="col-xl-2 col-sm-3 col-sm-2 col-form-label">Password</label>
                                                <div class="col-xl-10 col-lg-9 col-sm-10">
                                                    <input type="password" name="password" required class="form-control" placeholder="">
                                                </div>
                                            </div>
                                            <div class="form-group row mb-4">
                                                <label for="hPassword" class="col-xl-2 col-sm-3 col-sm-2 col-form-label">Phone</label>
                                                <div class="col-xl-10 col-lg-9 col-sm-10">
                                                    <input type="text" value="<?php
                                                    if (isset($_POST['phone'])) {
                                                        echo ($_POST['phone']);
                                                    }
                                                    ?>" class="form-control" name="phone" required placeholder="">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <div class="col-sm-10">
                                                    <button type="submit" class="btn btn-primary mt-3">Register</button>
                                                    <button type="button" onclick="window.location.href = 'index'" class="btn cursor btn-outline-primary mt-3" style="float: right">Cancel</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php require_once './partials/footer.php'; ?>
                </div>
                <!--  END CONTENT AREA  -->
            </div>
        </div>
        <!-- END MAIN CONTAINER -->
        <?php require_once './partials/scripts.php'; ?>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
        <script>
<?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"
                                                        });
        </script>

    </body>
</html>