<?php
ob_clean();
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';

function formatDateForDisplay($dateString) {
    if ($dateString === null || $dateString === '') return '';
    $dateObj = DateTime::createFromFormat('Y-m-d', $dateString);
    return $dateObj ? $dateObj->format('d-m-Y') : $dateString;
}


if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_role(['admin', 'superadmin']);
$user_id = $_SESSION['uid'] ?? 0;

$account_ids = $_POST['account_ids'] ?? [];
$clienteSeleccionado = $_POST['client_id'] ?? 'all';
$platformSeleccionada = $_POST['platform_id'] ?? 'todas';
$filtroEstado = $_POST['filter_expired'] ?? 'todas';

if (empty($account_ids)) {
    header("Content-Type: text/plain");
    die('Debe seleccionar al menos una cuenta.');
}

$account_ids = array_map('intval', $account_ids);
$placeholders = implode(',', array_fill(0, count($account_ids), '?'));

$params = [];
$sqlWhere = "WHERE 1=1 "; // condición base para concatenar filtros

if ($clienteSeleccionado !== '' && $clienteSeleccionado !== 'all') {
    $sqlWhere .= " AND a.client_id = ? ";
    $params[] = $clienteSeleccionado;
}
if ($platformSeleccionada !== '' && $platformSeleccionada !== 'todas') {
    $sqlWhere .= " AND a.platform_id = ? ";
    $params[] = $platformSeleccionada;
}
if ($filtroEstado === 'vencidas') {
    $sqlWhere .= " AND a.expiration_date < NOW() ";
} elseif ($filtroEstado === 'activas') {
    $sqlWhere .= " AND a.expiration_date >= NOW() ";
}

$sqlWhere .= " AND a.id IN ($placeholders) ";
$params = array_merge($params, $account_ids);

$sql = "
    SELECT a.id, a.email, a.price, a.expiration_date, u.name AS client_name, p.name AS platform_name
    FROM assigned_accounts a
    INNER JOIN users u ON a.client_id = u.id
    INNER JOIN platforms p ON a.platform_id = p.id
    $sqlWhere
    ORDER BY u.name, p.name, a.email
";

$stmt = pdo()->prepare($sql);
$stmt->execute($params);
$accounts = $stmt->fetchAll();

if (!$accounts) {
    header("Content-Type: text/plain");
    die('No se encontraron cuentas válidas para el reporte.');
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=reporte_cuentas.csv');
$output = fopen('php://output', 'w');

fputcsv($output, ['ID', 'Cliente', 'Plataforma', 'Correo', 'Fecha Expiración', 'Precio']);

$totalPrecio = 0;
foreach ($accounts as $acc) {
    fputcsv($output, [
        $acc['id'],
        $acc['client_name'],
        $acc['platform_name'],
        $acc['email'],
	formatDateForDisplay($acc['expiration_date']),
        number_format($acc['price'], 2),
    ]);
    $totalPrecio += $acc['price'];
}

fputcsv($output, ['', '', '', '', 'TOTAL', number_format($totalPrecio, 2)]);

fclose($output);
exit;
