<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';

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

try {
    $pdo = getConnection();
    
    // Construir a query base
    $query = "
        SELECT o.*, c.nome as cliente_nome
        FROM operacoes o
        JOIN clientes c ON o.cliente_id = c.id
        WHERE o.tipo = 'prova'
        AND o.deleted_at IS NULL
        AND (o.status = 'ativo' OR o.status IS NULL)  -- Apenas provas ativas
    ";
    
    $params = [];
    
    // Aplicar filtros
    if (!empty($_GET['dataInicio'])) {
        $query .= " AND DATE(o.created_at) >= ?";
        $params[] = $_GET['dataInicio'];
    }
    
    if (!empty($_GET['dataFim'])) {
        $query .= " AND DATE(o.created_at) <= ?";
        $params[] = $_GET['dataFim'];
    }
    
    if (!empty($_GET['cliente'])) {
        $query .= " AND o.cliente_id = ?";
        $params[] = $_GET['cliente'];
    }
    
    $query .= " ORDER BY o.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $provas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Buscar itens para cada prova
    foreach ($provas as &$prova) {
        $stmt = $pdo->prepare("
            SELECT oi.*, p.nome as produto_nome
            FROM operacao_itens oi
            JOIN produtos p ON oi.produto_id = p.id
            WHERE oi.operacao_id = ?
            AND oi.deleted_at IS NULL
        ");
        $stmt->execute([$prova['id']]);
        $prova['itens'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    echo json_encode([
        'success' => true,
        'data' => $provas
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Erro ao buscar provas: ' . $e->getMessage()
    ]);
}
