<?php

session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

include("../config/db.php");

$data = json_decode(file_get_contents("php://input"), true);

if (!$data) {
    echo json_encode(["success" => false, "message" => "Invalid JSON"]);
    exit;
}

if (!isset($data['full_name'], $data['email'], $data['password'])) {
    echo json_encode(["success" => false, "message" => "Missing fields"]);
    exit;
}

$full_name = $conn->real_escape_string($data['full_name']);
$email     = $conn->real_escape_string($data['email']);
$password  = password_hash($data['password'], PASSWORD_DEFAULT);


/* GENERATE UNIQUE REFERRAL CODE */

function generateReferralCode() {
    return "TAG" . strtoupper(substr(md5(uniqid()), 0, 6));
}

do {
    $referral_code = generateReferralCode();
    $checkCode = $conn->query("SELECT id FROM users WHERE referral_code='$referral_code'");
} while ($checkCode->num_rows > 0);


/* CHECK IF EMAIL EXISTS */

$check = $conn->query("SELECT id FROM users WHERE email='$email'");
if ($check->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Email already exists"]);
    exit;
}


/* INSERT USER */

$sql = "INSERT INTO users (full_name, email, password, referral_code)
        VALUES ('$full_name', '$email', '$password', '$referral_code')";

if ($conn->query($sql)) {

    echo json_encode([
        "success" => true,
        "referral_code" => $referral_code
    ]);

} else {

    echo json_encode([
        "success" => false,
        "message" => "Registration failed"
    ]);

}