<?php
session_start();
require_once '../layouts/dbconn.php';

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

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

// Verify user has permission to manage users
$current_user_id = $_SESSION['user_id'];
$current_user_role_sql = "SELECT ur.role_name, ur.role_id 
                          FROM users u 
                          JOIN user_roles ur ON u.role_id = ur.role_id 
                          WHERE u.user_id = ?";
$stmt = $conn->prepare($current_user_role_sql);
$stmt->bind_param("i", $current_user_id);
$stmt->execute();
$current_role_result = $stmt->get_result();
$current_user_role = $current_role_result->fetch_assoc();

$can_manage_users = false;
if ($current_user_role) {
    if ($current_user_role['role_name'] === 'Super Admin' || $current_user_role['role_name'] === 'Administrator') {
        $can_manage_users = true;
    } else {
        $perm_sql = "SELECT can_edit 
                     FROM role_permissions 
                     WHERE role_id = ? AND menu_id = (SELECT menu_id FROM menu_items WHERE menu_url = 'users.php' LIMIT 1)";
        $perm_stmt = $conn->prepare($perm_sql);
        $perm_stmt->bind_param("i", $current_user_role['role_id']);
        $perm_stmt->execute();
        $perm_result = $perm_stmt->get_result();
        $permissions = $perm_result->fetch_assoc();
        
        if ($permissions && $permissions['can_edit'] == 1) {
            $can_manage_users = true;
        }
    }
}

if (!$can_manage_users) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to manage users']);
    exit();
}

try {
    // Get and validate input
    $user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $new_status = isset($_POST['status']) ? trim($_POST['status']) : '';
    
    if (!$user_id) {
        throw new Exception('Invalid user ID');
    }
    
    if (!in_array($new_status, ['ACTIVE', 'INACTIVE', 'SUSPENDED', 'PENDING'])) {
        throw new Exception('Invalid status value');
    }
    
    // Prevent user from deactivating themselves
    if ($user_id == $current_user_id) {
        throw new Exception('You cannot change your own status');
    }
    
    // Verify user exists and get current details
    $check_sql = "SELECT user_id, full_name, status FROM users WHERE user_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('User not found');
    }
    
    $user = $result->fetch_assoc();
    $old_status = $user['status'];
    
    if ($old_status === $new_status) {
        throw new Exception('User already has this status');
    }
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Update user status
        $update_sql = "UPDATE users SET status = ?, updated_at = NOW() WHERE user_id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("si", $new_status, $user_id);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to update user status');
        }
        
        // If suspending user, log them out by clearing their session
        if ($new_status === 'SUSPENDED' || $new_status === 'INACTIVE') {
            // You might want to add a sessions table to track active sessions
            // For now, we'll just log the action
        }
        
        // Log the activity
        $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                    VALUES (?, 'UPDATE', 'user', ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $description = "Changed status from {$old_status} to {$new_status} for user: " . $user['full_name'];
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $log_stmt->bind_param("iisss", $current_user_id, $user_id, $description, $ip_address, $user_agent);
        $log_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        $status_display = ucfirst(strtolower($new_status));
        echo json_encode([
            'success' => true,
            'message' => "User status updated to {$status_display} successfully"
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>