<?php
session_start();
require_once '../../config.php';
require_once '../../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$action = $_POST['action'] ?? '';

if ($action !== 'change_role') {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit();
}

try {
    $agentId = intval($_POST['agent_id'] ?? 0);
    $newRole = trim($_POST['new_role'] ?? '');
    
    // Validate input
    if ($agentId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid agent ID']);
        exit();
    }
    
    if (empty($newRole) || $newRole !== 'agent') {
        echo json_encode(['success' => false, 'message' => 'Invalid role. Only "agent" role is supported.']);
        exit();
    }
    
    // Check if agent exists
    $stmt = $conn->prepare("SELECT id, username, role FROM agents WHERE id = ?");
    $stmt->bind_param("i", $agentId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Agent not found']);
        exit();
    }
    
    $agent = $result->fetch_assoc();
    $stmt->close();
    
    // Check if role is already the same
    if ($agent['role'] === $newRole) {
        echo json_encode(['success' => false, 'message' => 'Agent already has this role']);
        exit();
    }
    
    // Update the agent's role
    $updateStmt = $conn->prepare("UPDATE agents SET role = ?, updated_at = NOW() WHERE id = ?");
    $updateStmt->bind_param("si", $newRole, $agentId);
    
    if ($updateStmt->execute()) {
        $updateStmt->close();
        
        // Log the role change
        $logMessage = "Admin changed agent '{$agent['username']}' role from '{$agent['role']}' to '{$newRole}'";
        error_log($logMessage);
        
        $roleDisplay = ucfirst(str_replace('_', ' ', $newRole));
        echo json_encode([
            'success' => true,
            'message' => "Successfully changed {$agent['username']}'s role to {$roleDisplay}"
        ]);
    } else {
        $updateStmt->close();
        echo json_encode(['success' => false, 'message' => 'Failed to update agent role']);
    }
    
} catch (Exception $e) {
    error_log("Role change error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
