<?php
session_start();
header('Access-Control-Allow-Origin: *');
$vars = json_decode(file_get_contents("php://input"));

$requiredFields = ['firstName', 'lastName', 'email', 'phone', 'nin', 'password'];

// Validate required fields
foreach ($requiredFields as $field) {
    if (!isset($vars->$field) || empty($vars->$field)) {
        die(json_encode(["status" => false, "message" => ucfirst($field) . " is required or missing"]));
    }
}

// Validate email format
if (!filter_var($vars->email, FILTER_VALIDATE_EMAIL)) {
    die(json_encode(["status" => false, "message" => "Email is invalid"]));
}

// Validate phone length
if (strlen($vars->phone) != 11) {
    die(json_encode(["status" => false, "message" => "Phone number must be 11 digits"]));
}

// Validate password length
if (strlen($vars->password) < 8) {
    die(json_encode(["status" => false, "message" => "Password should be at least 8 characters long"]));
}

include "konnection.php";
include "func.php";

// Check if email or phone already exists
$checkEmailExists = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM `users` WHERE `email` = '$vars->email'"));
$checkPhoneExists = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM `users` WHERE `phone` = '$vars->phone'"));

if ($checkEmailExists) {
    die(json_encode(["status" => false, "message" => "Email already registered, try logging in"]));
}

if ($checkPhoneExists) {
    die(json_encode(["status" => false, "message" => "Phone number already registered, try logging in"]));
}

// Sanitize input
$firstName = mysqli_real_escape_string($conn, filter_var($vars->firstName, FILTER_SANITIZE_STRING));
$lastName = mysqli_real_escape_string($conn, filter_var($vars->lastName, FILTER_SANITIZE_STRING));
$nin = mysqli_real_escape_string($conn, filter_var($vars->nin, FILTER_SANITIZE_STRING));
$email = mysqli_real_escape_string($conn, filter_var($vars->email, FILTER_VALIDATE_EMAIL));
$phone = mysqli_real_escape_string($conn, filter_var($vars->phone, FILTER_SANITIZE_STRING));
$password = password_hash($vars->password, PASSWORD_DEFAULT);  // Secure password

// Generate API key and other values
$site_t = str_replace(' ', '', $site_title);
$apikey = "lv_" . $site_t . "_" . substr(str_shuffle("9876543210abcdegfhkjmnopqrstuvwxz987654311"), 0, 32);

$site = getSite();
if (!is_array($site) || $site["siteReg"] == 'OFF') {
    die(json_encode(["status" => false, "message" => "Site is not available"]));
}

$isBan = ($site["isBan"] === "ON") ? "1" : "0";
$canVerifyBVN = ($site["canVerifyBVN"] === "ON") ? "1" : "0";
$canVerifyNIN = ($site["canVerifyNIN"] === "ON") ? "1" : "0";

$status = "1";

// Create account with escaped table and column names
$createAccountQuery = mysqli_query($conn, "INSERT INTO `users` (`email`, `firstName`, `lastName`, `phone`, `password`, `userState`, `role`, `nin`, `isban`, `status`, `apiKey`, `canVerifyNIN`, `canVerifyBVN`) 
VALUES ('$email', '$firstName', '$lastName', '$phone', '$password', 'normalUser', 'AGENT', '$nin', '$isBan', '$status', '$apikey', '$canVerifyNIN', '$canVerifyBVN')");

if ($createAccountQuery) {
    mysqli_query($conn, "INSERT INTO `balance` (`user`, `amount`) VALUES ('$email', '0.00')");
    $_SESSION["user"] = $email;
    echo json_encode(["status" => true, "message" => "Account created"]);
} else {
    die(json_encode(["status" => false, "message" => "Error creating account: " . mysqli_error($conn)]));
}
