<?php
session_start();
require_once('config.php');
require 'email.php';

// Application Parameters
$error = NULL;
$is_consent_form_ok = 0;
$is_input_ok = 0;

// Input Sanitization
function sanitize($data) {
  	$data = trim($data);
  	$data = stripslashes($data);
  	$data = htmlspecialchars($data);
  	return $data;
}

/*
user table
- id
- email
- password
- confirm code
- is_confirmed
- banned

user_metadata
- id
- usr_id
- first_name
- last_name
- team_name
- affiliation
*/

if (isset($_POST['submit']) && isset($_FILES['consent_form'])) {
    // Connect to Database
	$connection = mysqli_connect($db_host, $db_username, $db_password);
	if (!$connection) die ("Could not connect to the database: <br />". mysqli_error());

    // Select Database
    $db_select=mysqli_select_db($connection, $db_database);
    if (!$db_select) die ("Could not select the database: <br />". mysqli_error());

    // Check User Inputs
    if (sanitize($_POST['first_name']) == NULL || sanitize($_POST['first_name']) == "") {
        $error = "Please enter a valid first name.";
    } else if (sanitize($_POST['last_name']) == NULL || sanitize($_POST['last_name']) == "") {
        $error = "Please enter a valid last name.";
    } else if (sanitize($_POST['email']) == NULL || sanitize($_POST['email']) == "") {
        // TODO: Add function to validate the email structure!
        $error = "Please enter a valid email address.";
    } else if (sanitize($_POST['password']) == NULL || sanitize($_POST['password']) == "") {
        $error = "Please eneter a valid password.";
    } else if (sanitize($_POST['team_name']) == NULL || sanitize($_POST['team_name']) == "") {
        $error = "Pleas enter a valid team name.";
    } else if (sanitize($_POST['affiliation']) == NULL || sanitize($_POST['affiliation']) == "") {
        $error = "Please enter a valid affiliation.";
    }
    else {
        $is_input_ok = 1;

        // Check Email Exist
        $email = sanitize($_POST['email']);
        $email_query = "SELECT * FROM users WHERE email = '$email';";
        $email_result = mysqli_query($connection, $email_query);
        if ($row = mysqli_fetch_array($email_result)) {
            $error = "An account has already been made with the provided email address.";
            $is_input_ok = 0;
        }

        // Check Team Name Exists
        $team_name = sanitize($_POST['team_name']);
        $name_query = "SELECT * FROM user_metadata WHERE team_name = '$team_name';";
        $name_result = mysqli_query($connection, $name_query);
        if ($row = mysqli_fetch_array($name_result)){
            $error = "The provided team name has already been taken.";
            $is_input_ok = 0;
        }
    }

    // Check Consent Form
    if (!isset($_FILES['consent_form']))
        $error = "Missing consent form.";
    else{
        $upload_error = $_FILES['consent_form']['error'];
        if ($upload_error !== UPLOAD_ERR_OK){
            if ($upload_error === UPLOAD_ERR_INI_SIZE || $upload_error === UPLOAD_ERR_FORM_SIZE)
                $error = "Consent form exceeds the maximum upload size.";
            else if ($upload_error === UPLOAD_ERR_NO_FILE)
                $error = "Missing consent form.";
            else if ($upload_error === UPLOAD_ERR_NO_TMP_DIR || $upload_error === UPLOAD_ERR_CANT_WRITE) {
                // Log technical details to server logs
                error_log("UPLOAD ERROR: Temporary directory issue detected");
                error_log("Error Code: " . $upload_error);
                error_log("Configured temp dir: " . ini_get('upload_tmp_dir'));
                error_log("Temp dir exists: " . (is_dir(ini_get('upload_tmp_dir')) ? 'YES' : 'NO'));
                error_log("Temp dir writable: " . (is_writable(ini_get('upload_tmp_dir')) ? 'YES' : 'NO'));
                if (function_exists('posix_getuid')) {
                    error_log("Process UID: " . posix_getuid());
                    error_log("Process GID: " . posix_getgid());
                }
                error_log("Server: " . $_SERVER['SERVER_NAME'] . " | Time: " . date('Y-m-d H:i:s'));

                // Also log to browser console for debugging
                echo "<script>console.log('UPLOAD ERROR: Temporary directory issue detected');</script>";
                echo "<script>console.log('Error Code: " . $upload_error . "');</script>";
                echo "<script>console.log('Configured temp dir: " . ini_get('upload_tmp_dir') . "');</script>";
                echo "<script>console.log('Temp dir exists: " . (is_dir(ini_get('upload_tmp_dir')) ? 'YES' : 'NO') . "');</script>";
                echo "<script>console.log('Temp dir writable: " . (is_writable(ini_get('upload_tmp_dir')) ? 'YES' : 'NO') . "');</script>";
                if (function_exists('posix_getuid')) {
                    echo "<script>console.log('Process UID: " . posix_getuid() . "');</script>";
                    echo "<script>console.log('Process GID: " . posix_getgid() . "');</script>";
                }
                echo "<script>console.log('Server: " . $_SERVER['SERVER_NAME'] . " | Time: " . date('Y-m-d H:i:s') . "');</script>";

                // Show generic user-friendly error instead
                $error = "File upload failed. Please try again or contact support if the problem persists.";
            } else
                $error = "Upload failed with error code: ".$upload_error.".";
        }
        else if (!is_uploaded_file($_FILES['consent_form']['tmp_name']))
            $error = "Missing consent form.";
        else{
            $filename = $_FILES['consent_form']['name'];
            $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if (!in_array($ext, $ext_allowed) )
                $error = "We only allow consent form in .pdf, .png, and .jpg, but get .".$ext;
            else if ($_FILES['consent_form']["size"] > 10485760)
                $error = "We only allow consent form smaller than 10MB.";
            else
                $is_consent_form_ok = 1;
        }
    }

    // Input user data into database
    if ($is_consent_form_ok == 1 && $is_input_ok == 1){
        // Generate Email Confirmation Code
        $confirm_code = uniqid();

        // Hash Password
        $password = hash('sha256', sanitize($_POST['password']));

        // Get the max idx as user id
        $query = "SELECT id FROM users ORDER BY id DESC limit 1;";
        $result = mysqli_query($connection, $query);
        $row = mysqli_fetch_array($result);
        $uid = $row['id'] + 1;

        // Save the consent form first
        $name_consent_form = $dir_consent_form . $uid . "." .$ext;
        if (move_uploaded_file($_FILES["consent_form"]["tmp_name"], $name_consent_form)){
            // Insert User Record
            $query = "INSERT INTO users (`id`, `email`, `password`, `confirm_code`, `is_confirmed`, `is_consentform_approved`, `is_admin`, `banned`, `pass_reset`) VALUES (".$uid.", '".$email."', '".$password."', '".$confirm_code."', FALSE, FALSE, FALSE, FALSE, FALSE);";
            $result = mysqli_query($connection, $query);

            // Insert User Metadata Record
            $query = "INSERT INTO user_metadata (`id`, `usr_id`, `first_name`, `last_name`, `team_name`, `affiliation`, `homepage`) VALUES (".$uid.", ".$uid.", '".sanitize($_POST['first_name'])."', '".sanitize($_POST['last_name'])."', '".sanitize($_POST['team_name'])."', '".sanitize($_POST['affiliation'])."', '".sanitize($_POST['homepage'])."');";
            $result = mysqli_query($connection, $query);

            // Send Confirmation Email
            $subject = 'Body Emotion Classification Challenge';
            $body = 'Hello '.sanitize($_POST['first_name']).",\r\n\nPlease click on the following link to confirm your account creation activation prcoess.\r\n$confirm_url$confirm_code\r\n\r\nRegards\r\nThe PSU Body Emotion Study Group";
            send_mail($email_user, $email_pass, $email, 'PSU Emotion Study Group', sanitize($_POST['first_name']) . ' ' . sanitize($_POST['last_name']), $subject, $body);

            // TEMP: Redirect to Registeration Success Page
            header('Location:./register_complete.php');
        } else {
            $error = "Failed to save the uploaded consent form.";
        }
    }

    // Database Connection
    $connection = mysqli_connect($db_host, $db_username, $db_password);
    if (!$connection){ die('Could not connect: ' . mysql_error()); }
    mysqli_select_db($connection, $db_database);
}

?>
<!DOCTYPE html>
<html>

<head>
    <script src="js/jquery-2.1.1.min.js"></script>
    <script src="js/header.js"></script>
    <style>
    .terms {
        overflow-y:scroll;
        overflow-x:hidden;
        height: 200px;
        width: 60%;
        border-style: solid;
        border-width: 2px;
        border-color: #7B7D7D;
        padding-left: 5px;
    }
    </style>
</head>

<body>
<!-- Navigation -->
<nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container">
        <script src="js/navibar.js"></script>
        <ul id="nav-mobile" class="right">
            <?php require_once('navigation.php'); ?>
        </ul>
    </div>
</nav>

<div class="section no-pad-bot">
    <form action="<?php echo(htmlentities($_SERVER['PHP_SELF'])); ?>" method="POST" enctype="multipart/form-data">
        <div class="container">
            <h5 class="header"><b>Account Registration</b></h5>
            <p><b>Note: </b>Teams that create more than one accounts may be banned from the compeition as it is a violation of the competition rules.</p>
            <?php if ($error) echo "<p style='color:red'><b>Error:</b> $error</p>" ?>
            <br />

            
                <div class="row">
                    <div class="input-field col s3">
                        <input id="first_name" type="text" class="validate" name="first_name" value="<?php if (!empty($_POST['first_name'])) echo $_POST['first_name'];?>">
                        <label for="first_name">First Name</label>
                    </div>
                    <div class="input-field col s3">
                        <input id="last_name" type="text" class="validate" name="last_name" value="<?php if (!empty($_POST['last_name'])) echo $_POST['last_name'];?>">
                        <label for="last_name">Last Name</label>
                    </div>
                </div>

                <div class="row">
                    <div class="input-field col s3">
                        <input id="email" type="text" class="validate" name="email" value="<?php if (!empty($_POST['email'])) echo $_POST['email'];?>">
                        <label for="email">Email Address</label>
                    </div>
                    <div class="input-field col s3">
                        <input id="password" type="password" class="validate" name="password" value="<?php if (!empty($_POST['password'])) echo $_POST['password'];?>">
                        <label for="password">Password</label>
                    </div>
                </div>

                <div class="row">
                    <div class="input-field col s6">
                        <input id="team_name" type="text" class="validate" name="team_name" value="<?php if (!empty($_POST['team_name'])) echo $_POST['team_name'];?>">
                        <label for="team_name">Team Name</label>
                    </div>
                </div>

                <div class="row">
                    <div class="input-field col s6">
                        <input id="affiliation" type="text" class="validate" name="affiliation" value="<?php if (!empty($_POST['affiliation'])) echo $_POST['affiliation'];?>">
                        <label for="affiliation">Affiliation</label>
                    </div>
                </div>

                <div class="row">
                    <div class="input-field col s6">
                        <input id="homepage" type="text" class="validate" name="homepage" value="<?php if (!empty($_POST['homepage'])) echo $_POST['homepage'];?>">
                        <label for="homepage">Homepage (Optional)</label>
                    </div>
                </div>

                <p><b>Please read, sign, and upload the following consent form:</b></p>

                <div class="input-field col s12">
                    <button type="button" style="width:400px" class="btn btn-primary" onclick="window.open('doc/consent_form.pdf')">Download the consent form</button><br/><br/>
                    <input type="file" style="width:400px" name="consent_form" class="btn btn-primary" id="consent_form"><br/><br />
                    <input type="submit" style="width:400px" name="submit" class="btn btn-primary" value="submit application"><br /><br /><br />
                </div>
            
        </div>
    </form>
</div>
</body>
<script src="js/footer.js"></script>
</html>
