<?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->admin_email) ||
    !isset($data->admin_password) ||
    !isset($data->name) ||
    !isset($data->email) ||
    !isset($data->password) ||
    !isset($data->role_type)
) {
    echo json_encode(["success" => false, "message" => "All fields are required"]);
    exit;
}

$admin_email   = trim($data->admin_email);
$admin_password = trim($data->admin_password);

$new_name      = trim($data->name);
$new_email     = trim($data->email);
$new_password  = trim($data->password);
$role_type     = trim($data->role_type); // Manager, SubAdmin, Custom

// Allowed roles
$valid_roles = ["Admin", "Manager", "SubAdmin", "Custom"];
if (!in_array($role_type, $valid_roles)) {
    echo json_encode(["success" => false, "message" => "Invalid role type"]);
    exit;
}

// ------------------------------
// STEP 1: VERIFY ADMIN LOGIN
// ------------------------------
$stmt = $conn->prepare("SELECT * FROM adminlogins WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $admin_email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "Admin not found"]);
    exit;
}

$admin = $result->fetch_assoc();

// Check password (plain for now)
if ($admin['password'] !== $admin_password) {
    echo json_encode(["success" => false, "message" => "Invalid admin credentials"]);
    exit;
}

// Check permission
if ($admin['userAccessLevel'] !== "superAdmin") {
    echo json_encode(["success" => false, "message" => "No permission to create roles"]);
    exit;
}

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

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

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

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

$stmt = $conn->prepare($sql);
$stmt->bind_param(
    "ssssss",
    $new_name,
    $new_email,
    $new_password,
    $newUid,
    $newEmpId,
    $role_type,
    ($role_type === "Admin" ? "superAdmin" : "subAdmin")
);

if ($stmt->execute()) {
    echo json_encode([
        "success" => true,
        "message" => "Role created successfully",
        "data" => [
            "username" => $new_name,
            "email"    => $new_email,
            "uid"      => $newUid,
            "empId"    => $newEmpId,
            "role"     => $role_type
        ]
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to create role"]);
}

exit;

?>
