<?php
session_start();
header('Content-Type: application/json');

// Include database connection
include '../layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit();
}

// Check permissions
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT HasPermission(?, 'agents_edit') as has_permission");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$permission_result = $stmt->get_result()->fetch_assoc();

if (!$permission_result['has_permission']) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Validate POST data
if (!isset($_POST['agent_id']) || !isset($_POST['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$agent_id = (int)$_POST['agent_id'];
$new_status = $_POST['status'];

// Validate status
$valid_statuses = ['ACTIVE', 'INACTIVE', 'SUSPENDED'];
if (!in_array($new_status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit();
}

try {
    $conn->begin_transaction();
    
    // Get current agent information
    $get_agent_sql = "SELECT full_name, status, agent_code FROM users WHERE user_id = ? AND agent_code IS NOT NULL";
    $get_stmt = $conn->prepare($get_agent_sql);
    $get_stmt->bind_param("i", $agent_id);
    $get_stmt->execute();
    $agent_info = $get_stmt->get_result()->fetch_assoc();
    
    if (!$agent_info) {
        throw new Exception('Agent not found');
    }
    
    $old_status = $agent_info['status'];
    
    // Update agent status
    $update_sql = "UPDATE users SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("si", $new_status, $agent_id);
    
    if (!$update_stmt->execute()) {
        throw new Exception('Failed to update agent status');
    }
    
    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent) 
               VALUES (?, 'STATUS_CHANGE', 'AGENT', ?, 'USER', ?, ?, ?, ?)";
    $log_stmt = $conn->prepare($log_sql);
    
    $old_values = json_encode(['status' => $old_status]);
    $new_values = json_encode([
        'status' => $new_status,
        'changed_by' => $_SESSION['full_name'],
        'agent_name' => $agent_info['full_name'],
        'agent_code' => $agent_info['agent_code']
    ]);
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $log_stmt->bind_param("iissss", $user_id, $agent_id, $old_values, $new_values, $ip_address, $user_agent);
    $log_stmt->execute();
    
    // Send notification to agent (optional)
    if ($new_status === 'SUSPENDED') {
        // Send suspension notification
        $notification_sql = "INSERT INTO communication_log (recipient_type, recipient_id, communication_type, subject, message, status) 
                           VALUES ('AGENT', ?, 'EMAIL', 'Account Status Update', ?, 'PENDING')";
        $notification_stmt = $conn->prepare($notification_sql);
        $message = "Your agent account has been suspended. Please contact your supervisor for more information.";
        $notification_stmt->bind_param("is", $agent_id, $message);
        $notification_stmt->execute();
    } elseif ($new_status === 'ACTIVE' && $old_status !== 'ACTIVE') {
        // Send reactivation notification
        $notification_sql = "INSERT INTO communication_log (recipient_type, recipient_id, communication_type, subject, message, status) 
                           VALUES ('AGENT', ?, 'EMAIL', 'Account Reactivated', ?, 'PENDING')";
        $notification_stmt = $conn->prepare($notification_sql);
        $message = "Your agent account has been reactivated. You can now access the platform.";
        $notification_stmt->bind_param("is", $agent_id, $message);
        $notification_stmt->execute();
    }
    
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Agent status updated successfully',
        'old_status' => $old_status,
        'new_status' => $new_status
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>