<?php
require_once "config.php"; // DB connection

function get_value($key) {
    return $_POST[$key] ?? $_GET[$key] ?? '';
}

// User input
$FullName     = get_value('FullName');
$Username     = get_value('Username');
$Email        = get_value('Email');
$Number       = get_value('Number');
$Password     = get_value('Password');
$DeviceID     = get_value('DeviceID');
$PersonalKey  = get_value('PersonalKey');
$AccountTrype = get_value('AccountTrype') ?: 'User';

// Validate required fields
if (empty($FullName) || empty($Username) || empty($Email) || empty($Number) || empty($Password) || empty($DeviceID) || empty($PersonalKey)) {
    echo json_encode(["status" => "error", "message" => "All fields are required"]);
    exit;
}

// Check if Username exists
$stmt = $conn->prepare("SELECT id FROM ZabbarUser WHERE Username = ?");
$stmt->bind_param("s", $Username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    echo json_encode(["status" => "error", "message" => "Username already exists"]);
    exit;
}
$stmt->close();

// Check if Email exists
$stmt = $conn->prepare("SELECT id FROM ZabbarUser WHERE Email = ?");
$stmt->bind_param("s", $Email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    echo json_encode(["status" => "error", "message" => "Email already registered"]);
    exit;
}
$stmt->close();

// Check if PersonalKey exists
$stmt = $conn->prepare("SELECT id FROM ZabbarUser WHERE PersonalKey = ?");
$stmt->bind_param("s", $PersonalKey);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    echo json_encode(["status" => "error", "message" => "PersonalKey already used"]);
    exit;
}
$stmt->close();

// Check if Number used >=3 times
$stmt = $conn->prepare("SELECT COUNT(*) FROM ZabbarUser WHERE Number = ?");
$stmt->bind_param("s", $Number);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();

if ($count >= 3) {
    echo json_encode(["status" => "error", "message" => "Number already used 3 times"]);
    exit;
}

// Insert user
$stmt = $conn->prepare("INSERT INTO ZabbarUser (FullName, Username, Email, Number, Password, DeviceID, PersonalKey, AccountTrype) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssss", $FullName, $Username, $Email, $Number, $Password, $DeviceID, $PersonalKey, $AccountTrype);

if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "Signup successful"]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to register user"]);
}

$stmt->close();
$conn->close();
?>