<?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";

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

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

$admin_id = intval($data["admin_id"]);

try {
    // -----------------------
    // 1️⃣ Update adminlogins table
    // -----------------------
    $fields = [
        "username", "email", "gender", "dob", "password", "pin", "number",
        "address", "website", "company_name", "company_address", "company_number",
        "db_prefex", "status", "profile_pic", "empId", "userDepartment",
        "userRole", "userAccessLevel", "role_id"
    ];

    $set = [];
    $types = "";
    $values = [];

    foreach ($fields as $f) {
        if (isset($data[$f])) {
            $set[] = "$f = ?";
            $types .= is_int($data[$f]) ? "i" : "s";
            $values[] = $data[$f];
        }
    }

    if (!empty($set)) {
        $sql = "UPDATE adminlogins SET " . implode(", ", $set) . " WHERE client_index = ?";
        $types .= "i";
        $values[] = $admin_id;

        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$values);
        $stmt->execute();
    }

    // -----------------------
    // 2️⃣ Update roles table if role_id provided
    // -----------------------
    if (isset($data["role_id"]) && isset($data["roleType"])) {
        $role_id = intval($data["role_id"]);
        $role_name = $data["roleType"];
        $role_access_type = $data["role_access_type"] ?? "full";
        $role_description = $data["role_description"] ?? "";

        $role_stmt = $conn->prepare("
            UPDATE roles 
            SET name = ?, access_type = ?, description = ?
            WHERE id = ?
        ");
        $role_stmt->bind_param("sssi", $role_name, $role_access_type, $role_description, $role_id);
        $role_stmt->execute();
    }

    echo json_encode([
        "success" => true,
        "message" => "Admin and role updated successfully"
    ]);

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