<?php

require_once __DIR__ . '/../core/api.php';
global $pdo;

$month = $_GET['month'] ?? date('Y-m');
$action = $_GET['action'] ?? 'csv';

try {
    $sql = "SELECT 
                t.*, 
                CONCAT(c.first_name, ' ', c.last_name) as client_name
            FROM transactions t
            LEFT JOIN clients c ON t.client_id = c.id
            WHERE DATE_FORMAT(t.transaction_date, '%Y-%m') = :month
            ORDER BY t.transaction_date ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['month' => $month]);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error BD: " . $e->getMessage());
}

// ==========================================
// OPCIÓN A: EXCEL (CSV)
// ==========================================
if ($action === 'csv') {
    $filename = "Reporte_Financiero_$month.csv";
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename);
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); 
    
    fputcsv($output, ['ID', 'FECHA', 'TIPO', 'DESCRIPCION', 'CLIENTE/PROVEEDOR', 'MONTO ($)', 'COMPROBANTE']);
    
    $ing = 0; $gas = 0;
    foreach ($transactions as $row) {
        $estadoDoc = !empty($row['receipt_file']) ? 'Sí' : 'No';
        $type_es = ($row['transaction_type'] === 'income') ? 'ingreso' : 'gasto'; // Mapeo a español
        $contact_name = $row['client_name'] ?: ($row['provider_name'] ?: 'General');

        fputcsv($output, [
            $row['id'], $row['transaction_date'], strtoupper($type_es),
            $row['description'], $contact_name,
            number_format($row['amount'], 2, '.', ''), $estadoDoc
        ]);
        
        if ($row['transaction_type'] === 'income') $ing += $row['amount']; else $gas += $row['amount'];
    }
    
    fputcsv($output, []);
    fputcsv($output, ['', '', '', '', 'INGRESOS', number_format($ing, 2)]);
    fputcsv($output, ['', '', '', '', 'GASTOS', number_format($gas, 2)]);
    fputcsv($output, ['', '', '', '', 'NETO', number_format($ing - $gas, 2)]);
    fclose($output);
    exit;
}

// ==========================================
// OPCIÓN B: ZIP
// ==========================================
if ($action === 'zip') {
    if (!class_exists('ZipArchive')) die("Error: ZipArchive no instalado en PHP.");

    $zip = new ZipArchive();
    $zipFilename = "Comprobantes_$month.zip";
    $tempFile = tempnam(sys_get_temp_dir(), 'zip_fin');
    
    if ($zip->open($tempFile, ZipArchive::CREATE) !== TRUE) die("Error creando ZIP temporal.");

    $count = 0;
    foreach ($transactions as $row) {
        if (!empty($row['receipt_file'])) {
            $serverPath = __DIR__ . '/../' . $row['receipt_file'];
            
            if (file_exists($serverPath)) {
                $ext = pathinfo($serverPath, PATHINFO_EXTENSION);
                $cleanDesc = substr(preg_replace('/[^A-Za-z0-9]/', '_', $row['description']), 0, 30);
                $zipName = $row['transaction_date'] . "_" . $cleanDesc . "." . $ext;
                
                $zip->addFile($serverPath, $zipName);
                $count++;
            }
        }
    }
    $zip->close();

    if ($count === 0) {
        header('Content-Type: text/plain');
        echo "No se encontraron archivos físicos para descargar en $month.";
        exit;
    }

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipFilename);
    header('Content-Length: ' . filesize($tempFile));
    readfile($tempFile);
    unlink($tempFile);
    exit;
}