<?php
/**
 * Admin Actions AJAX Handler
 * Handles all admin management actions
 */
define('ROVO_APP', true);
require_once '../../config.php';
require_once '../../Auth.php';

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

if (!$auth->hasRole('super_admin')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (!isset($_POST['csrf_token']) || !Security::validateCSRFToken($_POST['csrf_token'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid CSRF token']);
    exit;
}

$action = $_POST['action'] ?? '';
$admin_id = (int)($_POST['admin_id'] ?? 0);

try {
    switch ($action) {
        case 'update_permissions':
            $permissions = [
                'can_create' => isset($_POST['can_create']) ? 1 : 0,
                'can_edit' => isset($_POST['can_edit']) ? 1 : 0,
                'can_delete' => isset($_POST['can_delete']) ? 1 : 0,
                'can_view' => 1,
                'can_manage_users' => isset($_POST['can_manage_users']) ? 1 : 0,
                'can_manage_payments' => isset($_POST['can_manage_payments']) ? 1 : 0,
                'can_manage_properties' => isset($_POST['can_manage_properties']) ? 1 : 0,
                'can_verify_documents' => isset($_POST['can_verify_documents']) ? 1 : 0
            ];
            
            // Check if permissions exist
            $existing = $db->fetchOne("SELECT admin_id FROM admin_permissions WHERE admin_id = ?", [$admin_id]);
            
            if ($existing) {
                $sql = "UPDATE admin_permissions SET 
                        can_create = ?, can_edit = ?, can_delete = ?,
                        can_manage_users = ?, can_manage_payments = ?,
                        can_manage_properties = ?, can_verify_documents = ?,
                        updated_at = NOW()
                        WHERE admin_id = ?";
                
                $result = $db->execute($sql, [
                    $permissions['can_create'], $permissions['can_edit'], $permissions['can_delete'],
                    $permissions['can_manage_users'], $permissions['can_manage_payments'],
                    $permissions['can_manage_properties'], $permissions['can_verify_documents'],
                    $admin_id
                ]);
            } else {
                $sql = "INSERT INTO admin_permissions 
                        (admin_id, can_create, can_edit, can_delete, can_view,
                        can_manage_users, can_manage_payments, can_manage_properties, can_verify_documents) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $result = $db->execute($sql, [
                    $admin_id,
                    $permissions['can_create'], $permissions['can_edit'], $permissions['can_delete'],
                    $permissions['can_view'], $permissions['can_manage_users'],
                    $permissions['can_manage_payments'], $permissions['can_manage_properties'],
                    $permissions['can_verify_documents']
                ]);
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Permissions updated successfully'
            ]);
            break;
            
        case 'suspend':
            $sql = "UPDATE users SET status = 'suspended' WHERE id = ? AND role != 'super_admin'";
            $result = $db->execute($sql, [$admin_id]);
            
            if ($result > 0) {
                // Log activity
                $user = $db->fetchOne("SELECT first_name, last_name FROM users WHERE id = ?", [$admin_id]);
                $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                        VALUES (?, 'suspend_admin', 'user', ?, ?, ?, ?)";
                $db->execute($sql, [
                    $auth->getCurrentUser()['id'],
                    $admin_id,
                    "Admin {$user['first_name']} {$user['last_name']} suspended",
                    Security::getClientIP(),
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Admin suspended successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to suspend admin'
                ]);
            }
            break;
            
        case 'activate':
            $sql = "UPDATE users SET status = 'active' WHERE id = ? AND role != 'super_admin'";
            $result = $db->execute($sql, [$admin_id]);
            
            if ($result > 0) {
                // Log activity
                $user = $db->fetchOne("SELECT first_name, last_name FROM users WHERE id = ?", [$admin_id]);
                $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                        VALUES (?, 'activate_admin', 'user', ?, ?, ?, ?)";
                $db->execute($sql, [
                    $auth->getCurrentUser()['id'],
                    $admin_id,
                    "Admin {$user['first_name']} {$user['last_name']} activated",
                    Security::getClientIP(),
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Admin activated successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to activate admin'
                ]);
            }
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
    }
} catch (Exception $e) {
    error_log("Admin action error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred. Please try again.'
    ]);
}