<?php
	
	$DATABASE_HOST = '';
	$DATABASE_USER = '';
	$DATABASE_PASS = '';
	$DATABASE_NAME = '';
	include __DIR__.'/../config.php'; //import db config
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
    exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$stmt = $con->query("SHOW COLUMNS FROM accounts__authentication LIKE 'question_1'");
// In this case we can use the account ID to get the account info.

$row = $stmt->fetch_row();
$questions_string = $row[1];
//echo($questions_string[0]);
$stmt->close();
preg_match("/^enum\(\'(.*)\'\)$/", $questions_string, $matches);
$questions1 = explode("','", $matches[1]);


$stmt = $con->query("SHOW COLUMNS FROM accounts__authentication LIKE 'question_2'");
// In this case we can use the account ID to get the account info.

$row = $stmt->fetch_row();
$questions_string = $row[1];
//echo($questions_string[0]);
$stmt->close();
preg_match("/^enum\(\'(.*)\'\)$/", $questions_string, $matches);
$questions2 = explode("','", $matches[1]);


$stmt = $con->query("SHOW COLUMNS FROM accounts__authentication LIKE 'question_3'");
// In this case we can use the account ID to get the account info.

$row = $stmt->fetch_row();
$questions_string = $row[1];
//echo($questions_string[0]);
$stmt->close();
preg_match("/^enum\(\'(.*)\'\)$/", $questions_string, $matches);
$questions3 = explode("','", $matches[1]);

?>
<!doctype html>
<html class="no-js" lang="" xmlns="http://www.w3.org/1999/html">

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta property="og:title" content="">
    <meta property="og:type" content="">
    <meta property="og:url" content="">
    <meta property="og:image" content="">

    <link rel="manifest" href="site.webmanifest">
    <link rel="apple-touch-icon" href="icon.png">
    <!-- Place favicon.ico in the root directory -->

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/registration.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <style>
        .ui-autocomplete {
            max-height: 100px;
            overflow-y: auto;
            /* prevent horizontal scrollbar */
            overflow-x: hidden;
        }

        /* IE 6 doesn't support max-height
          * we use height instead, but this forces the menu to always be this tall
          */
        * html .ui-autocomplete {
            height: 100px;
        }

        .container {
            padding: 60px 0;
            max-width: 650px;
            margin: auto;
        }
    </style>
    <meta name="theme-color" content="#fafafa">
</head>

<body>
<div id="user_reg" class="container-sm">
        <form id="regForm" method="post">
            <div class="form-header-group">
                <h1 class="form-header">STARS New Site Registration</h1>
                <div class="form-subheader">Please complete the form below to register</div>
            </div>
            <hr>

            <label for="attendee_contact" class="form-label">Please enter your profile information below <span class="form-required">*</span></label>
            <div class="input-group" id="attendee_contact">
                <input type="text" id="first_name" name="first_name" class="form-text" placeholder="First Name" required>
                <input type="text" id="last_name" name="last_name" class="form-text" placeholder="Last Name" required>
                <input type="email" id="current_email" name="current_email" class="form-text" placeholder="E-mail Address" required>
            </div>
            <label for="authentication" class="form-label">
                Please create a password and enter it below.
            </label>
            <span class="form-subheader">Password must be a minimum of 8 characters and can use any combination of letters, numbers, and special characters</span>
            <div class="input-group" id="authentication">
                <input type="password"
                       name="password" id="password" placeholder="Password" />
                <input class="form-control" type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" required>
                <button id="togglePassword" name="togglePassword">
                    <i class="fa fa-eye" style="color: black" name="toggleIcon" id="toggleIcon"></i>
                   </button>
            </div>

            <div class="input-group" id="security_questions">
                <div class="form-subheader">Select, and provide answers to, three security questions below.</div>

                    <select class="form-select-sm" id="question1" name="question1">
                        <option value="" selected readonly> ----- </option>
                        <?php
                        foreach ($questions1 as $q){
                            echo "<option value=\"{$q}\">" . $q . "</option>";
                        }
                        ?>
                    </select>
                    <input type="text" id="answer1" name="answer1">


                    <select class="form-select-sm" id="question2" name="question2">
                        <option value="" selected readonly> ----- </option>
                        <?php
                        foreach ($questions2 as $q){
                            echo "<option value=\"{$q}\">" . $q . "</option>";
                        }
                        ?>
                    </select>
                    <input type="text" id="answer2" name="answer2">

                    <select class="form-select-sm" id="question3" name="question3">
                        <option value="" selected readonly> ----- </option>
                        <?php
                        foreach ($questions3 as $q){
                            echo "<option value=\"{$q}\">" . $q . "</option>";
                        }
                        ?>
                    </select>
                    <input type="text" id="answer3" name="answer3">

            </div>
            <label for="school_name" class="form-label">Search for School/Organization by Name or Acronym<span class="form-required">*</span></label>
            <input type="textarea" rows="2" id="school_name" name="school_name" class="form-control"
                   placeholder="Start typing to search" required>

                <!--<hr>
                <div class="button">
                    <a href="reg_form.php" class="submit-button" id="reg_submit" style="display: none">Sign Up</a>
                    <a href="user_confirm.html" class="submit-button" id="user_search" name="user_search" style="display: none">Find Me</a>
                </div>-->



            <label for="re" class="form-label">Race/Ethnicity<span class="form-required">*</span></label>
            <select class="form-select" id="re" name="re" aria-label="Race/Ethnicity" required>
                <option selected disabled value="">Choose...</option>
                <option value="hispanic_or_latino">Hispanic or Latino</option>
                <option value="white">White</option>
                <option value="black">Black or African American</option>
                <option value="asian_pacific_islander">Asian or Pacific Islander</option>
                <option value="native_hawaiian_american_indian_alaskan_native">Native Hawaiian or Other Pacific Islander, American Indian or Alaska Native</option>
                <option value="multi_racial">Two or more races/ethnicities</option>
                <option value="other">Other</option>
                <option value="not-specified">I would prefer not to specify</option>
            </select>
            <label for="gender" class="form-label">Gender<span class="form-required">*</span></label>
            <select class="form-select" id="gender" name="gender" aria-label="Gender" required>
                <option selected disabled value="">Choose...</option>
                <option value="male">Male</option>
                <option value="female">Female</option>
                <option value="other">Other</option>
                <option value="not-specified">I would prefer not to specify</option>
            </select>
            <label for="school_role" class="form-label">What is your role at your school/company<span
                    class="form-required">*</span></label>
            <select class="form-select" id="school_role" name="school_role" aria-label="Type" required>
                <option selected disabled value="">Choose</option>
                <option value="faculty_staff"> Faculty/Academic Staff </option>
                <option value="phd_student"> PhD Student </option>
                <option value="masters_student"> Masters Student </option>
                <option value="4yr_undergrad"> Undergraduate Student (4 year degree program) </option>
                <option value="2yr_undergrad"> Undergraduate Student (2 year degree program at a community college) </option>
                <option value="industry"> Professional/Industry </option>
                <option value="other"> Other </option>
            </select>
            <label for="stars_role" class="form-label">STARS Role<span class="form-required">*</span></label>
            <select class="form-select" id="stars_role" name="stars_role" aria-label="Role" required>
                <option selected disabled value="">Choose...</option>
                <option value="faculty">Faculty</option>
                <option value="stars_slc_student">STARS SLC Student</option>
                <option value="stars_slc_leader">STARS SLC Leader</option>
                <option value="stars_pi">STARS PI</option>
	            <option value="researcher_evaluator">Researcher/Evaluator</option>
            </select>
            <label class="form-label" for="current_celebration">I have registered for STARS Celebration 2022 by September 1st!</label>
            <input type="checkbox" id="current_celebration" name="current_celebration" value="current_celebration">
            <label for="current_celebration"> Yes</label><br>
            <div id="starsbefore">
                <label for="prev_user" class="form-label">Have you or your school ever participated in a STARS event
                    before?<span class="form-required">*</span></label>
                <input type="checkbox" id="prev_user" name="prev_user">
                <label for="prev_user"> Yes</label><br>
                <div id="prev_user_div" style="display: none">

                <label for="prev_year" class="form-label-sm"> I remember the year! (Optional)</label>
                    <input placeholder="Year" id="prev_year" name="prev_year" type="number" maxlength="4" min="2000">

                <label for="prev_school" class="form-label-sm"> I was at a different school/university (Optional)</label>
                    <input type="text" rows="2" id="prev_school" name="prev_school" class="form-control"
                           placeholder="Select School or Type Company Name" >
                    <button id="user_search" name="user_search">Find Me!</button>
                    <span>Your new registration will soon be linked with prior STARS data.<br> Additional update requests/operations will be available on the home page</span>
                </div>
	            <div id="user_options" style="display: none">
		            <hr>
		
		            <span>We could not find an exact match. Possible matches are below</span>
		            <select id="possible_matches" name="possible_matches">
			           
		            </select>
	            </div>
	            <div id="user_confirm" style="display: none">
		            <input type="text" hidden="hidden" id="prev_id" name="prev_id">
                    <div class="input-group row" id="user_contacts">
                        <div class="col">
                            <label for="prevFirstName" class="form-label"> First Name:</label>
                            <input type="text" id="prevFirstName" name="prevFirstName" class="form-text">
                        </div>
	                    <div class="col">
                            <label for="prevLastName" class="form-label"> Last Name: </label>
                            <input type="text" id="prevLastName" name="prevLastName" class="form-text">
                        </div>
                    </div>
	                <div class="input-group row" id="emailandschool">
                        <div class="col">
                            <label for="prevEmail" class="form-label">Email:</label>
                            <input type="text" id="prevEmail" name="prevEmail" style="width: 100%">

                            <label for="school_name" class="form-label">School:</label>
                            <input type="text" id="prev_school_name" name="prev_school_name" style="width: 100%">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <label for="firstEventInfo" class="form-label">First STARS Event</label>
                            <dl class="col" id="firstEventInfo">

                                <dt>Event: </dt>
                                <dd id="firstEventName"></dd>
                                <dt>Date: </dt>
                                <dd id="firstEventDate"></dd>
                            </dl>
                        </div>
                        <div class="col">
                            <label for="latestEventInfo" class="form-label">Latest STARS Event</label>
                            <dl class="col" id="latestEventInfo">

                                <dt>Event: </dt>
                                <dd id="latestEventName"></dd>
                                <dt>Date: </dt>
                                <dd id="latestEventDate"></dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
            <hr>

            <div class="button">
                <button type="submit" class="submit-button" id="reg_submit">Submit Registration</button>
            </div>

        </form>
    </div>

<script src="js/vendor/modernizr-3.11.2.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" integrity="sha256-lSjKY0/srUM9BE3dPm+c4fBo1dky2v27Gdjm2uoZaL0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
<script>
    function sendRegistration() {
        console.log("Reached form send")
        $.ajax({
            type: "POST",
            url: "server/register.php",
            data: {
                //FORM DATA HERE
                first_name: $('#first_name').val().toLowerCase(),
                last_name: $('#last_name').val().toLowerCase(),
                email: $('#current_email').val(),
                school_name: $('#school_name').val(),
                re: $('#re').val(),
                gender: $('#gender').val(),
                school_role: $('#school_role').val(),
                stars_role: $('#stars_role').val(),
                password: $('#password').val(),
                question1: $('#question1').val(),
                answer1: $('#answer1').val(),
                question2: $('#question2').val(),
                answer2: $('#answer2').val(),
                question3: $('#question3').val(),
                answer3: $('#answer3').val(),
                prev_year: $('#firstEventDate').text(),
                prev_school: $('#prev_school').val(),
	            prev_id: $('#possible_matches').val()=='' ? $('#prev_id').val() : $('#possible_matches').val(),
                curr_reg: $('#current_celebration').checked ? '1' : '0'
            },
            async: false,
            dataType: "json",
            error: function (data) {
                console.log(data);
            },
            success: function (data) {
                alert('User Successfully Registered!')
                var url = 'home.php';
                window.location.href = url;
            }
        });
    }

    function searchPreviousUser() {
        $.ajax({
            type: "POST",
            url: "server/user_search.php",
            data: {
                //FORM DATA HERE
                first_name: $('#first_name').val(),
                last_name: $('#last_name').val(),
                email: $('#current_email').val(),
                prev_year: $('#prev_year').val(),
                prev_school: $('#prev_school').val()
            },
            async: false,
            dataType: "json",
            success: function (data) {
                var userInfo = document.getElementById("user_confirm")
	            var userOptions = document.getElementById("user_options")
                var regForm = document.getElementById("user_reg")
                if (data[0].length===0){
                    alert(
                        "There was an error finding your information in our database. Please fill the rest registration form for now"
                    )
                } else {
					var results = data[0]
	                if(results[0]["email"]){
		                //first STARS event for a user
		                let prev = data[0][0]
		                $('#prev_id').val(prev["id"])
		                //latest STARS event for a user (or first event again if they've only been to one)
		                let latest = data[0].length > 1 ? data[0][data[0].length-1] : prev
		                let email = prev["email"]!=='' ? prev["email"] : latest["email"]
		                let prev_school = latest["Carnegie_name"]!=='' ? latest["Carnegie_name"] : prev["Carnegie_name"]
		
		                $('#prevFirstName').val(prev["first"].charAt(0).toUpperCase() + prev["first"].slice(1))
		                $('#prevLastName').val(prev["last"].charAt(0).toUpperCase() + prev["last"].slice(1))
		                $('#prevEmail').val(email)
		                $('#prev_school_name').val(prev_school)
		                var first_event = {
			                name: prev["src_yr"],
			                date: prev["registration_yr"]
		                }
		                var latest_event = {
			                name: latest["src_yr"],
			                date: latest["registration_yr"]
		                }
		                $('#firstEventName').text(first_event.name)
		                $('#firstEventDate').text(first_event.date)
		                $('#latestEventName').text(latest_event.name)
		                $('#latestEventDate').text(latest_event.date)
		                userInfo.style.display = "block"
	                } else {
						//the results are a set of possible matches
		                for (const res of results){
			                $('#possible_matches').append($('<option>', {
				                value: res["id"],
				                text : titleCase(res["first"]) + " " + titleCase(res["last"])
			                }));
		                }
		                $('#possible_matches').append($('<option>', {
			                value: 0,
			                text : "None of these match"
		                }));
						userOptions.style.display="block"
	                }
                 
                }
                //userInfoDiv.innerHTML = "First Name: "+data["first_name"]+"<br>Last Name: "+data["last_name"]
            },
            error: function (data) {
                console.log(data)
                alert(
                    "There was an error finding your information in our database. Please fill the rest registration form for now"
                )
            }
        });
    }
    function titleCase(string){
	    return string[0].toUpperCase() + string.slice(1).toLowerCase();
    }

    function togglePassword(){
        var type = $('#password').attr("type");
        console.log(type);
        if(type === "password"){
            $('#password').attr("type","text");
            $('#confirm_password').attr("type", "text");
        }else if(type === "text"){
            $('#password').attr("type","password");
            $('#confirm_password').attr("type","password");
        }
        $('#toggleIcon').toggleClass('fa-eye-slash')

    }

    $(function () {
        $("#regForm").on("submit", function (event) {
            event.preventDefault()
            sendRegistration()
        })
        $("#school_name").autocomplete({
            source: "server/school_search.php",
            minLength: 3
        });
        $("#prev_user").on("click", function (event){
            event.preventDefault()
            document.getElementById("prev_user_div").style.display = "block"
        })
        $("#user_search").on("click", function (event) {
            event.preventDefault()
            searchPreviousUser()
        })
        $("#togglePassword").click(function (event) {
            event.preventDefault()
            togglePassword()
        });
    })
</script>
</body>

</html>