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

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

include_once 'config.php'; // DB connection

$response = ["success" => false, "message" => "Invalid request"];
$data = json_decode(file_get_contents("php://input"));

// ------------------------------
// REQUIRED INPUT FIELDS
// ------------------------------
if (
    !isset($data->name) ||
    !isset($data->email) ||
    !isset($data->password)
) {
    echo json_encode(["success" => false, "message" => "Name, email, and password are required"]);
    exit;
}

$name     = trim($data->name);
$email    = trim($data->email);
$password = trim($data->password);

// ------------------------------
// STEP 1: CHECK IF ADMIN EMAIL EXISTS
// ------------------------------
$check = $conn->prepare("SELECT email FROM adminlogins WHERE email = ? LIMIT 1");
$check->bind_param("s", $email);
$check->execute();
$result = $check->get_result();

if ($result->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Email already exists"]);
    exit;
}

// ------------------------------
// STEP 2: GENERATE UNIQUE UID + EMPID
// ------------------------------
$newUid   = "UID" . rand(100000, 999999);
$newEmpId = "EMP" . rand(100000, 999999);

// ------------------------------
// STEP 3: CREATE SUPER ADMIN
// ------------------------------
$sql = "
INSERT INTO adminlogins
(username, email, password, pin, number, address, uid, empId, userDepartment, userRole, userAccessLevel, status, date)
VALUES (?, ?, ?, '0000', '', 'noAddress', ?, ?, 'General', 'Admin', 'superAdmin', 'active', NOW())
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $name, $email, $password, $newUid, $newEmpId, $role);

$role = "Admin"; // Always admin

if ($stmt->execute()) {
    echo json_encode([
        "success" => true,
        "message" => "New Admin created successfully",
        "data" => [
            "username" => $name,
            "email"    => $email,
            "uid"      => $newUid,
            "empId"    => $newEmpId,
            "userRole" => "Admin",
            "userAccessLevel" => "superAdmin"
        ]
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to create admin"]);
}

exit;
?>
