<?php
require 'vendor/autoload.php'; // Ruta a autoload.php de PhpSpreadsheet

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Datos de conexi��n
include '../config/bd.php';

try {
    // Conexi��n a la base de datos
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Obtener datos
    $stmt = $pdo->prepare("SELECT transaction_name, package_name, amount, date_time FROM transactions");
    $stmt->execute();
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Crear hoja de c��lculo
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // Encabezados
    $sheet->setCellValue('A1', 'Nro');
    $sheet->setCellValue('B1', 'Nombre Completo');
    $sheet->setCellValue('C1', 'Medio de Pago');
    $sheet->setCellValue('D1', 'Monto');
    $sheet->setCellValue('E1', 'Fecha de Registro');

    // Llenar datos
    $row = 2;
    $orderNumber = 1;
    foreach ($transactions as $transaction) {
        // Cambiar el nombre del paquete seg��n el valor
        $packageName = $transaction['package_name'] === 'com.bcp.innovacxion.yapeapp' ? 'Yape' : 
                      ($transaction['package_name'] === 'com.bcp.bank.bcp' ? 'Transferencia BCP' : $transaction['package_name']);
        
        $sheet->setCellValue("A$row", $orderNumber);
        $sheet->setCellValue("B$row", $transaction['transaction_name']);
        $sheet->setCellValue("C$row", $packageName);
        $sheet->setCellValue("D$row", $transaction['amount']);
        $sheet->setCellValue("E$row", $transaction['date_time']);
        
        $row++;
        $orderNumber++;
    }

    // Generar archivo Excel
    $writer = new Xlsx($spreadsheet);
    $fileName = 'transacciones.xlsx';

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    $writer->save('php://output');
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
