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

require_once '../config/conexao.php';

try {
    $pdo = getConnection();
    
    // Recebe o período
    $periodo = isset($_GET['periodo']) ? $_GET['periodo'] : '7dias';
    
    // Define a data inicial com base no período
    switch ($periodo) {
        case 'hoje':
            $dataInicial = date('Y-m-d 00:00:00');
            $dataFinal = date('Y-m-d 23:59:59');
            break;
        case 'ontem':
            $dataInicial = date('Y-m-d 00:00:00', strtotime('-1 day'));
            $dataFinal = date('Y-m-d 23:59:59', strtotime('-1 day'));
            break;
        case '7dias':
            $dataInicial = date('Y-m-d 00:00:00', strtotime('-7 days'));
            $dataFinal = date('Y-m-d 23:59:59');
            break;
        case '30dias':
            $dataInicial = date('Y-m-d 00:00:00', strtotime('-30 days'));
            $dataFinal = date('Y-m-d 23:59:59');
            break;
        default:
            throw new Exception('Período inválido');
    }
    
    // Busca as vendas por dia
    $query = "
        SELECT 
            DATE(created_at) as data,
            COUNT(*) as quantidade,
            SUM(valor_total) as total
        FROM operacoes
        WHERE tipo = 'venda'
        AND status = 'ativo'
        AND afeta_caixa = 1
        AND deleted_at IS NULL
        AND created_at BETWEEN ? AND ?
        GROUP BY DATE(created_at)
        ORDER BY data DESC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$dataInicial, $dataFinal]);
    $vendas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $vendas
    ]);

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