<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$tipo = $_GET['tipo'] ?? '';
$formato = $_GET['formato'] ?? 'csv';

function exportCSV($data, $filename) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, array_keys($data[0] ?? []), ';');
    
    foreach ($data as $row) {
        fputcsv($output, $row, ';');
    }
    fclose($output);
}

switch($tipo) {
    case 'clientes':
        $stmt = $pdo->query("SELECT id, nome, documento, telefone, email, endereco_cidade, plano, status FROM clientes");
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        exportCSV($data, 'clientes');
        break;
        
    case 'os':
        $stmt = $pdo->query("SELECT * FROM vw_os_completa ORDER BY data_abertura DESC");
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        exportCSV($data, 'ordens_servico');
        break;
        
    case 'estoque':
        $stmt = $pdo->query("SELECT * FROM materiais ORDER BY nome");
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        exportCSV($data, 'estoque');
        break;
}