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

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if the user has sufficient permissions (super admin only)
$admin_level = $_SESSION['admin_level'] ?? 0;
if ($admin_level < 9) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get admin ID from POST request
$admin_id = $_POST['admin_id'] ?? '';

// Validate required field
if (empty($admin_id)) {
    echo json_encode(['success' => false, 'message' => 'Admin ID is required']);
    exit();
}

// Don't allow deleting yourself
if ($admin_id == $_SESSION['admin_id']) {
    echo json_encode(['success' => false, 'message' => 'You cannot delete your own account']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Check if admin exists
    $stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
    $stmt->execute([$admin_id]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$admin) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => 'Admin not found']);
        exit();
    }
    
    // Don't allow deleting the last super admin
    if ($admin['admin_level'] >= 9) {
        // Check if this is the last super admin
        $stmt = $conn->prepare("SELECT COUNT(*) FROM admins WHERE admin_level >= 9 AND id != ?");
        $stmt->execute([$admin_id]);
        $superAdminCount = $stmt->fetchColumn();
        
        if ($superAdminCount === 0) {
            $conn->rollBack();
            echo json_encode(['success' => false, 'message' => 'Cannot delete the last super admin']);
            exit();
        }
    }
    
    // Check for admin's activity
    $stmt = $conn->prepare("
        SELECT COUNT(*) FROM admin_logs 
        WHERE admin_id = ? AND created_at > DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
    ");
    $stmt->execute([$admin_id]);
    $recentActivity = $stmt->fetchColumn();
    
    // If there's recent activity, soft delete instead of hard delete
    if ($recentActivity > 0) {
        $stmt = $conn->prepare("
            UPDATE admins SET
                status = 'deleted',
                email = CONCAT(email, '.deleted.', UNIX_TIMESTAMP()),
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ");
        $stmt->execute([$admin_id]);
        
        $deleteType = 'soft';
    } else {
        // Delete admin permissions
        $stmt = $conn->prepare("DELETE FROM admin_permissions WHERE admin_id = ?");
        $stmt->execute([$admin_id]);
        
        // Delete admin from the database
        $stmt = $conn->prepare("DELETE FROM admins WHERE id = ?");
        $stmt->execute([$admin_id]);
        
        $deleteType = 'hard';
    }
    
    // Log the action
    $stmt = $conn->prepare("
        INSERT INTO admin_logs (admin_id, action, details, created_at)
        VALUES (?, ?, ?, CURRENT_TIMESTAMP)
    ");
    $stmt->execute([
        $_SESSION['admin_id'],
        $deleteType === 'soft' ? 'soft_delete_admin' : 'delete_admin',
        ($deleteType === 'soft' ? 'Soft deleted' : 'Deleted') . ' admin: ' . $admin['name'] . ' (' . $admin['email'] . ')'
    ]);
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Admin ' . ($deleteType === 'soft' ? 'deactivated' : 'deleted') . ' successfully',
        'delete_type' => $deleteType
    ]);
    
} catch (PDOException $e) {
    if (isset($conn)) {
        $conn->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
