<?php
/**
 * DEACTIVATE USER - deactivate_user.php
 * Copy this as deactivate_user.php
 */
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$user_id = $_GET['id'] ?? 0;

// Prevent self-deactivation
if ($user_id == $_SESSION['user_id']) {
    $_SESSION['error_message'] = "You cannot deactivate your own account!";
    header('Location: list_users.php');
    exit();
}

// Get user details
$sql = "SELECT CONCAT(first_name, ' ', last_name) as full_name, status FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "User not found!";
    header('Location: list_users.php');
    exit();
}

$user = $result->fetch_assoc();

// Update user status to inactive
$update_sql = "UPDATE users SET status = 'inactive', updated_at = NOW() WHERE id = ?";
$update_stmt = $conn->prepare($update_sql);
$update_stmt->bind_param("i", $user_id);

if ($update_stmt->execute()) {
    // Log activity
    $activity_sql = "INSERT INTO activity_logs (user_id, action_type, module, reference_id, new_values) 
                   VALUES (?, 'UPDATE', 'USER', ?, ?)";
    $activity_stmt = $conn->prepare($activity_sql);
    $new_values = json_encode(['status' => 'inactive', 'deactivated_by' => $_SESSION['user_id']]);
    $activity_stmt->bind_param("iis", $_SESSION['user_id'], $user_id, $new_values);
    $activity_stmt->execute();
    
    $_SESSION['success_message'] = "User '{$user['full_name']}' deactivated successfully!";
} else {
    $_SESSION['error_message'] = "Failed to deactivate user!";
}

header('Location: list_users.php');
exit();
?>