<?php
include_once 'main.class.php';

$db = new DBMain();
$missing_params = [];

if (!isset($_GET['username'])) {
    $missing_params[] = 'USERNAME';
}

if (!isset($_GET['password'])) {
    $missing_params[] = 'PASSWORD';
}

if (!isset($_GET['user_type'])) {
    $missing_params[] = 'USER TYPE';
}

if (!isset($_GET['email'])) {
    $missing_params[] = 'EMAIL';
}

if (!isset($_GET['clients_id'])) {
    $missing_params[] = 'NO CLIENTS SELECTED';
}

if (!empty($missing_params)) {
    echo 'Error: Missing Information [' . implode(', ', $missing_params) . ']';
    exit;
}

// hashing the password
$passowrd = hash('sha256', $_GET['password']);

// checking the database if user and password exists

$result = $db->exec_query('safesure_users', ['*'], '', '', '', '', 'safesure_users_name="' . $_GET['username'] . '" AND password="' . $passowrd . '"');
// if exists return already exists and point to the user page with the user record id
if ($result->num_rows > 0) {
    echo 'Error: User Already Exists |' . $result->fetch_assoc()['record_id'];
    exit;
}


// insert into user table

$insert = $db->insert("INSERT INTO `safesure_users` (`safesure_users_name`,`password`,`user_type_id`,`email`,`clients_multi`,`name`,`assessor_number`,`moderator_number`) VALUES ('" . $_GET['username'] . "', '" . $passowrd . "', '" . $_GET['user_type'] . "', '" . $_GET['email'] . "', '" . $_GET['clients_id'] . "', '" . $_GET['name'] . "', '" . $_GET['assessor_number'] . "', '" . $_GET['moderator_number'] . "')");

// check if insert was successfull

if ($insert) {
    echo 'Success';
} else {
    echo "Error: Insert Failed [INSERT INTO `safesure_users` (`safesure_users_name`,`password`,`user_type_id`,`email`,`clients_multi`,`name`,`assessor_number`,`moderator_number`) VALUES ('" . $_GET['username'] . "', '" . $passowrd . "', '" . $_GET['user_type'] . "', '" . $_GET['email'] . "', '" . $_GET['clients_id'] . "', '" . $_GET['name'] . "', '" . $_GET['assessor_number'] . "', '" . $_GET['moderator_number'] . "')]";
}
