<?php
    $validation_errors = array();
    $password_pattern = "/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/";
    $email_pattern = "/\w+@\w+\.\w+/";
   
    $username = $_POST["username"];
    $password = $_POST["password"];
    $confirm_password = $_POST["confirm-password"];
    $first_name = $_POST["first-name"];
    $last_name = $_POST["last-name"];
    $address_one = $_POST["address-one"];
    $address_two = $_POST["address-two"];
    $city = $_POST["city"];
    $state = $_POST["state"];
    $zip_code = $_POST["zip-code"];
    $phone_number = $_POST["phone-number"];
    $email = $_POST["email"];
    $gender = $_POST["gender"];
    $marital_status = $_POST["marital-status"];
    $birth_date = $_POST["birth-date"];
    $servername = "localhost:3306";
    $sql_username = "root";
    $sql_password = "";
    $dbname = "project";
    if (strlen($address_two) === 0) {
        $address_two = "Not provided";
    }
    $sql_statement = "INSERT INTO 
    project.registration (userName
        , password
        , firstName 
        , lastName 
        , address1
        , address2 
        , city
        , state 
        , zipCode
        , phone 
        , email 
        , gender 
        , maritalStatus 
        , dateOfBirth) 
    VALUES ('$username'
        , '$password'
        , '$first_name'
        , '$last_name'
        , '$address_one'
        , '$address_two'
        , '$city'
        , '$state'
        , '$zip_code'
        , '$phone_number'
        , '$email'
        , '$gender'
        , '$marital_status'
        , '$birth_date')";

    $required_fields = array(
        $username,
        $password,
        $confirm_password,
        $first_name,
        $last_name,
        $address_one,
        $city,
        $state
    );

    $max_lengths = array(
        $username => 50,
        $password => 50,
        $confirm_password => 50,
        $first_name => 50,
        $last_name => 50,
        $address_one => 100,
        $address_two => 100,
        $city => 50,
        $state => 52,
        $zip_code => 10,   
    );

    $min_lengths = array(
        $username => 6,
        $password => 8,
        $confirm_password => 8,
        $zip_code => 5,
    );

    function handleFormSubmit() {
        validateForm();
        global $validation_errors;
        if (count($validation_errors) > 1) {
            echo count($validation_errors);
            $validation_message = "Some errors were found in the following fields: ";
            foreach($validation_errors as $error) {
                $validation_message = "$error error";
            }
            return $validation_message;      
        }
        else {
            $userId = insertRecords();
            $get_info = "?userId=$userId";
            header("Location: confirmation.php".$get_info);
            exit();
        }
        
    }

    function validateForm() {
        global $validation_errors;
        validateRequiredFields();
        validateMaxLengths();
        validateMinLengths();
        global $password;
        global $password_pattern;
        global $email;
        global $email_pattern;
        $isPasswordValid = preg_match($password_pattern, $password);
        $isEmailValid = preg_match($email_pattern, $email);
        if (!$isPasswordValid) {
            array_push($validation_errors, $password);
        }       
        if (!$isEmailValid) {
            array_push($validation_errors, $email);
        }
    }

    function validateRequiredFields() {
        global $required_fields;
        global $validation_errors;
        foreach($required_fields as $field) {
            if(empty($field)) {
                echo $field;
                array_push($validation_errors, $field);
            }
        }
    }

    function validateMaxLengths() {
        global $max_lengths;
        global $validation_errors;
        foreach($max_lengths as $key => $value) {
            if (strlen($key) > $value) {
                echo $key;
                array_push($$validation_errors, $key);
            }
        }
    }

    function validateMinLengths() {
        global $min_lengths;
        global $validation_errors;
        foreach($min_lengths as $key => $value) {
            if (strlen($key) < $value) {
                echo $key;
                array_push($validation_errors, $key);
            }
        }
    }

    function insertRecords() {
        global $servername, $sql_username, $sql_password, $dbname, $sql_statement, $address_two;
        global $username;
        echo $sql_statement;
        $conn = mysqli_connect($servername, $sql_username, $sql_password, $dbname);
        if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
        }
        if (mysqli_query($conn, $sql_statement)) {
            $last_id = mysqli_insert_id($conn);
            return $last_id;
          } else {
            echo "Error: " . $sql_statement . "<br>" . mysqli_error($conn);
          }

    }
?>

<html>
    <?php echo handleFormSubmit() ?>
</html>