<?php
header('Content-Type: application/json');
require_once 'config.php';

// Check authentication and authorization
requireRole(['Admin']);

if ($_SERVER['REQUEST_METHOD'] !== 'DELETE') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

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

// Validate input
if (!isset($data['id'])) {
    http_response_code(400);
    die(json_encode(['error' => 'Missing required field: id']));
}

try {
    $db = getDB();
    
    // Prevent deactivating the only admin
    $adminCount = $db->query('SELECT COUNT(*) as cnt FROM users WHERE role = \'Admin\' AND is_active = 1')->fetch(PDO::FETCH_ASSOC)['cnt'];
    
    $stmt = $db->prepare('SELECT role FROM users WHERE id = ?');
    $stmt->execute([$data['id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        http_response_code(404);
        die(json_encode(['error' => 'User not found']));
    }
    
    if ($user['role'] === 'Admin' && $adminCount <= 1) {
        http_response_code(400);
        die(json_encode(['error' => 'Cannot deactivate the only admin user']));
    }
    
    // Deactivate user (soft delete)
    $updateStmt = $db->prepare('
        UPDATE users 
        SET is_active = 0, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
    ');
    $updateStmt->execute([$data['id']]);
    
    http_response_code(200);
    die(json_encode([
        'success' => true,
        'message' => 'User deactivated successfully'
    ]));
    
} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode(['error' => 'Database error: ' . $e->getMessage()]));
}
