<?php
ob_start();
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if (isset($_GET['id'])) {
            getAdminById($_GET['id']);
        } else {
            getAllAdmins();
        }
        break;
    case 'POST':
        createAdmin();
        break;
    case 'PUT':
        updateAdmin();
        break;
    case 'DELETE':
        deleteAdmin();
        break;
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}

function getAllAdmins() {
    $db = getDB();
    
    $stmt = $db->query("
        SELECT 
            a.id,
            a.username,
            a.full_name,
            a.email,
            a.role_id,
            a.is_active,
            a.last_login,
            a.created_at,
            r.display_name as role_name
        FROM admin_users a
        LEFT JOIN roles r ON a.role_id = r.id
        ORDER BY a.created_at DESC
    ");
    
    $admins = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'data' => $admins
    ]);
}

function getAdminById($id) {
    $db = getDB();
    
    $stmt = $db->prepare("
        SELECT 
            a.id,
            a.username,
            a.full_name,
            a.email,
            a.role_id,
            a.is_active,
            a.last_login,
            a.created_at,
            r.display_name as role_name
        FROM admin_users a
        LEFT JOIN roles r ON a.role_id = r.id
        WHERE a.id = ?
    ");
    
    $stmt->execute([$id]);
    $admin = $stmt->fetch();
    
    if ($admin) {
        echo json_encode([
            'success' => true,
            'data' => $admin
        ]);
    } else {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Usuario no encontrado'
        ]);
    }
}

function createAdmin() {
    $db = getDB();
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validación
    if (empty($data['username']) || empty($data['password']) || empty($data['email']) || empty($data['role_id'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Faltan campos obligatorios'
        ]);
        return;
    }
    
    // Verificar si el usuario ya existe
    $stmt = $db->prepare("SELECT id FROM admin_users WHERE username = ? OR email = ?");
    $stmt->execute([$data['username'], $data['email']]);
    if ($stmt->fetch()) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'El usuario o email ya existe'
        ]);
        return;
    }
    
    // Hash de contraseña
    $passwordHash = password_hash($data['password'], PASSWORD_BCRYPT);
    
    // Insertar usuario
    $stmt = $db->prepare("
        INSERT INTO admin_users (username, password_hash, full_name, email, role_id, is_active)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $data['username'],
        $passwordHash,
        $data['full_name'] ?? '',
        $data['email'],
        $data['role_id'],
        isset($data['is_active']) ? ($data['is_active'] ? 't' : 'f') : 't'
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Usuario creado correctamente',
        'id' => $db->lastInsertId()
    ]);
}

function updateAdmin() {
    $db = getDB();
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'ID de usuario requerido'
        ]);
        return;
    }
    
    // Construir query dinámicamente
    $fields = [];
    $values = [];
    
    if (!empty($data['username'])) {
        $fields[] = "username = ?";
        $values[] = $data['username'];
    }
    
    if (!empty($data['full_name'])) {
        $fields[] = "full_name = ?";
        $values[] = $data['full_name'];
    }
    
    if (!empty($data['email'])) {
        $fields[] = "email = ?";
        $values[] = $data['email'];
    }
    
    if (!empty($data['password'])) {
        $fields[] = "password_hash = ?";
        $values[] = password_hash($data['password'], PASSWORD_BCRYPT);
    }
    
    if (isset($data['role_id'])) {
        $fields[] = "role_id = ?";
        $values[] = $data['role_id'];
    }
    
    if (isset($data['is_active'])) {
        $fields[] = "is_active = ?";
        $values[] = $data['is_active'] ? 't' : 'f';
    }
    
    if (empty($fields)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'No hay campos para actualizar'
        ]);
        return;
    }
    
    $values[] = $data['id'];
    
    $sql = "UPDATE admin_users SET " . implode(', ', $fields) . " WHERE id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute($values);
    
    echo json_encode([
        'success' => true,
        'message' => 'Usuario actualizado correctamente'
    ]);
}

function deleteAdmin() {
    $db = getDB();
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'ID de usuario requerido'
        ]);
        return;
    }
    
    // No permitir eliminar el usuario admin principal
    if ($data['id'] == 1) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'No se puede eliminar el usuario administrador principal'
        ]);
        return;
    }
    
    $stmt = $db->prepare("DELETE FROM admin_users WHERE id = ?");
    $stmt->execute([$data['id']]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Usuario eliminado correctamente'
    ]);
}
