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

include_once __DIR__ . "/config.php";

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

$required = ["username", "email", "password", "roleType"];
foreach ($required as $field) {
    if (!isset($data[$field]) || $data[$field] === "") {
        echo json_encode(["success" => false, "message" => "Missing field: $field"]);
        exit;
    }
}

$username  = $data["username"];
$email     = $data["email"];
$password  = $data["password"]; // Always hash!
$roleType  = $data["roleType"];

// Generate IDs
$uid   = uniqid("U_", true);
$empId = "EMP_" . strtoupper(substr(uniqid(), -6));

try {
    $conn->begin_transaction();

    // Check duplicate email
    $chk = $conn->prepare("SELECT 1 FROM adminlogins WHERE email = ?");
    $chk->bind_param("s", $email);
    $chk->execute();
    if ($chk->get_result()->num_rows > 0) {
        echo json_encode(["success" => false, "message" => "Email already exists"]);
        exit;
    }

    // Get role_id
    $role_q = $conn->prepare("SELECT id, access_type FROM roles WHERE name = ?");
    $role_q->bind_param("s", $roleType);
    $role_q->execute();
    $role_r = $role_q->get_result();
    if ($role_r->num_rows == 0) {
        echo json_encode(["success" => false, "message" => "Role not found"]);
        exit;
    }
    $role = $role_r->fetch_assoc();
    $role_id = $role['id'];
    $access_type = $role['access_type'];

    // Insert Admin
    $stmt = $conn->prepare("
        INSERT INTO adminlogins 
        (uid, empId, username, email, password, userRole, userAccessLevel, role_id, date, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), 'active')
    ");
    $stmt->bind_param(
        "sssssssi",
        $uid, $empId, $username, $email, $password,
        $roleType, $access_type, $role_id
    );
    $stmt->execute();

    $conn->commit();

    echo json_encode([
        "success" => true,
        "message" => "Admin created successfully and linked to role permissions",
        "admin_id" => $stmt->insert_id,
        "role_id" => $role_id,
        "uid" => $uid,
        "empId" => $empId
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        "success" => false,
        "message" => "Server error",
        "error" => $e->getMessage()
    ]);
}
?>