<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

session_start();

require __DIR__ . '/classes/Database.php';
require __DIR__ . '/classes/lib.php';
$db_connection = new Database();
$conn = $db_connection->dbConnection();

// DATA FORM REQUEST
$data = json_decode(file_get_contents("php://input"));
$returnData = new CMsg(0);

if ($_SERVER["REQUEST_METHOD"] != "POST") 
{
    $returnData = new CMsg(0, 404, 'Page Not Found! REQUEST_METHOD');
    echo $returnData->jsonarray();
    return;
}

if (
    !isset($data->email)
    || !isset($data->password)
    || empty(trim($data->email))
    || empty(trim($data->password))
) 
{

    $fields = ['fields' => ['email', 'password']];
    $returnData = new CMsg(0, 422, 'Please Fill in all Required Fields!', $fields);
    echo $returnData->jsonarray();
    return;
}

// IF THERE ARE NO EMPTY FIELDS THEN-
$email = trim($data->email);
$password = trim($data->password);

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    $returnData = new CMsg(0, 422, 'Invalid Email Address!');
    echo $returnData->jsonarray();
    return;
}

if (strlen($password) < 8)
{
    $returnData = new CMsg(0, 422, 'Your password must be at least 8 characters long!');
    echo $returnData->jsonarray();
    return;
} 

try 
{
    $maxtries = 100000; // prevent endless loop, most unlikely 
    $tries = 0;

    $qr_id = random_str(6);
    $count = 1;
    while($count >= 1 && $tries < $maxtries)
    {
        $qr_id = random_str(6);

        $check_qr_id = "SELECT `qr_id` FROM `dogs` WHERE `qr_id`=:qr_id";
        $check_qr_id_stmt = $conn->prepare($check_qr_id);
        $check_qr_id_stmt->bindValue(':qr_id', $qr_id, PDO::PARAM_STR);
        $check_qr_id_stmt->execute();

        $count = $check_qr_id_stmt->rowCount();
        ++$tries;
    }
    if ($tries >= $maxtries) 
    {
        $result = new CMsg(
            0, 
            507, 
            'Too many registered users on the server, try it again later'); 
    }
    else
    {
        $insert_query = "INSERT INTO `dogs`(`qr_id`,`email`,`password`) VALUES(:qr_id,:email,:password)";

        $insert_stmt = $conn->prepare($insert_query);

        // DATA BINDING
        $insert_stmt->bindValue(':qr_id', htmlspecialchars(strip_tags($qr_id)), PDO::PARAM_STR);
        $insert_stmt->bindValue(':email', $email, PDO::PARAM_STR);
//        $insert_stmt->bindValue(':password', $password, PDO::PARAM_STR);
        $insert_stmt->bindValue(':password', password_hash($password, PASSWORD_DEFAULT), PDO::PARAM_STR);

        $insert_stmt->execute();

        $returnData = new CMsg(1, 201, 'You have successfully registered.');
    }

} 
catch (PDOException $e) 
{
    $returnData = new CMsg(0, 500, $e->getMessage());
}

echo $returnData->jsonarray();
?>
