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

ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

include_once __DIR__ . "/config.php";

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

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

$admin_id   = (int)$data['admin_id'];
$username   = trim($data['username'] ?? '');
$email      = trim($data['email'] ?? '');
$password   = $data['password'] ?? '';
$roleType   = trim($data['roleType'] ?? '');  // ← This is what you send!
$status     = $data['status'] ?? 'active';

// At least one field to update
if ($username === '' && $email === '' && $password === '' && $roleType === '' && !in_array($status, ['active', 'inactive'])) {
    echo json_encode(["success" => false, "message" => "Nothing to update"]);
    exit;
}

try {
    $conn->begin_transaction();

    // 1. Check admin exists
    $check = $conn->prepare("SELECT client_index, email FROM adminlogins WHERE client_index = ?");
    $check->bind_param("i", $admin_id);
    $check->execute();
    $result = $check->get_result();
    if ($result->num_rows === 0) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Admin not found"]);
        exit;
    }
    $current = $result->fetch_assoc();

    // 2. Email duplicate check (skip if same as current)
    if ($email !== '' && strtolower($email) !== strtolower($current['email'])) {
        $email_check = $conn->prepare("SELECT 1 FROM adminlogins WHERE email = ? AND client_index != ?");
        $email_check->bind_param("si", $email, $admin_id);
        $email_check->execute();
        if ($email_check->get_result()->num_rows > 0) {
            $conn->rollback();
            echo json_encode(["success" => false, "message" => "Email already used"]);
            exit;
        }
    }

    // 3. If roleType is provided → get role_id and access_type
    $role_id = null;
    $access_type = null;
    if ($roleType !== '') {
        $role_q = $conn->prepare("SELECT id, access_type FROM roles WHERE name = ?");
        $role_q->bind_param("s", $roleType);
        $role_q->execute();
        $role_res = $role_q->get_result();
        if ($role_res->num_rows === 0) {
            $conn->rollback();
            echo json_encode(["success" => false, "message" => "Role '$roleType' not found"]);
            exit;
        }
        $role = $role_res->fetch_assoc();
        $role_id = $role['id'];
        $access_type = $role['access_type'];
    }

    // 4. Build dynamic UPDATE
    $updates = [];
    $params = [];
    $types = '';

    if ($username !== '') { $updates[] = "username = ?"; $params[] = $username; $types .= 's'; }
    if ($email !== '')    { $updates[] = "email = ?";    $params[] = $email;    $types .= 's'; }
    if ($password !== '') { 
        $updates[] = "password = ?"; 
        $params[] = password_hash($password, PASSWORD_DEFAULT); 
        $types .= 's'; 
    }
    if ($role_id !== null) {
        $updates[] = "role_id = ?";         $params[] = $role_id;      $types .= 'i';
        $updates[] = "userRole = ?";        $params[] = $roleType;     $types .= 's';
        $updates[] = "userAccessLevel = ?"; $params[] = $access_type;  $types .= 's';
    }
    if (in_array($status, ['active', 'inactive'])) {
        $updates[] = "status = ?"; $params[] = $status; $types .= 's';
    }

    $params[] = $admin_id;
    $types .= 'i';

    $set_clause = implode(", ", $updates);
    $sql = "UPDATE adminlogins SET $set_clause WHERE client_index = ?";

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

    $conn->commit();

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

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