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

include_once __DIR__ . "/config.php";

// Read POST JSON body
$data = json_decode(file_get_contents("php://input"), true);
$email = $data['email'] ?? '';

if (!$email) {
    echo json_encode([
        "success" => false,
        "message" => "Email is required"
    ]);
    exit;
}

// Get the admin and role info
$stmt = $conn->prepare("SELECT role_id, userRole, userAccessLevel FROM adminlogins WHERE email=? LIMIT 1");
$stmt->bind_param("s", $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();
$role_id = $admin['role_id'];

// Default empty permissions
$permissions = [];

// Only fetch permissions if role_id exists
if ($role_id) {
    $perm_sql = "
        SELECT p.name, p.module
        FROM permissions p
        INNER JOIN role_permissions rp ON p.id = rp.permission_id
        WHERE rp.role_id = ?
    ";
    $perm_stmt = $conn->prepare($perm_sql);
    $perm_stmt->bind_param("i", $role_id);
    $perm_stmt->execute();
    $perm_result = $perm_stmt->get_result();

    while ($row = $perm_result->fetch_assoc()) {
        $permissions[] = $row;
    }
}

echo json_encode([
    "success" => true,
    "role" => $admin['userRole'],
    "access_type" => $admin['userAccessLevel'],
    "permissions" => $permissions
]);
