<?php
include '../config/bd.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $whereConditions = [];
    $params = [];

    if (!empty($_GET['nombre'])) {
        $whereConditions[] = "transaction_name LIKE ?";
        $params[] = '%' . $_GET['nombre'] . '%';
    }

    if (!empty($_GET['fecha'])) {
        $whereConditions[] = "DATE(date_time) = ?";
        $params[] = $_GET['fecha'];
    }

    if (!empty($_GET['monto_min']) && is_numeric($_GET['monto_min'])) {
        $whereConditions[] = "amount >= ?";
        $params[] = floatval($_GET['monto_min']);
    }

    if (!empty($_GET['codigo_seguridad'])) {
        $whereConditions[] = "security_code LIKE ?";
        $params[] = '%' . $_GET['codigo_seguridad'] . '%';
    }

    $sql = "SELECT id, transaction_name, package_name, amount, security_code, date_time 
            FROM transactions";
    
    if (!empty($whereConditions)) {
        $sql .= " WHERE " . implode(" AND ", $whereConditions);
    }
    
    $sql .= " ORDER BY date_time DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $transacciones = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $contador = 1;
    foreach ($transacciones as $row) {
        $medioPago = ($row['package_name'] == 'com.bcp.innovacxion.yapeapp') ? 'Yape' : 'Otro';
        $fechaFormateada = date('d/m/Y H:i', strtotime($row['date_time']));
        $montoFormateado = 'S/ ' . number_format($row['amount'], 2);
        $codigoSeguridad = !empty($row['security_code']) ? $row['security_code'] : '-';
        
        echo "<tr>";
        echo "<td class='fw-bold text-primary'>{$contador}</td>";
        echo "<td class='fw-medium'>" . htmlspecialchars($row['transaction_name']) . "</td>";
        echo "<td><span class='badge bg-success'>{$medioPago}</span></td>";
        echo "<td class='fw-bold text-success'>{$montoFormateado}</td>";
        echo "<td class='text-center'>";
        
        if ($codigoSeguridad !== '-') {
            echo "<span class='badge bg-info'>{$codigoSeguridad}</span>";
        } else {
            echo "<span class='text-muted'>-</span>";
        }
        
        echo "</td>";
        echo "<td class='text-muted'>{$fechaFormateada}</td>";
        echo "</tr>";
        
        $contador++;
    }

    if (empty($transacciones)) {
        echo "<tr>";
        echo "<td colspan='6' class='text-center text-muted py-4'>";
        echo "<i class='fas fa-search me-2'></i>";
        echo "No se encontraron transacciones con los filtros aplicados";
        echo "</td>";
        echo "</tr>";
    }

} catch (PDOException $e) {
    echo "<tr>";
    echo "<td colspan='6' class='text-center text-danger py-4'>";
    echo "<i class='fas fa-exclamation-triangle me-2'></i>";
    echo "Error en la consulta";
    echo "</td>";
    echo "</tr>";
}
?>