<?php
ob_clean();
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../vendor/autoload.php';
use Dompdf\Dompdf;

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

// Filtro por cliente si se seleccionó
if ($clienteSeleccionado !== '' && $clienteSeleccionado !== 'all') {
    $sqlWhere .= " AND a.client_id = ? ";
    $params[] = $clienteSeleccionado;
}

// Filtro por plataforma si es diferente a 'todas'
if ($platformSeleccionada !== '' && $platformSeleccionada !== 'todas') {
    $sqlWhere .= " AND a.platform_id = ? ";
    $params[] = $platformSeleccionada;
}

// Filtro por estado de cuenta
if ($filtroEstado === 'vencidas') {
    $sqlWhere .= " AND a.expiration_date < NOW() ";
} elseif ($filtroEstado === 'activas') {
    $sqlWhere .= " AND a.expiration_date >= NOW() ";
}

// Filtro por IDs seleccionados
$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.');
}

$html = '<h3 style="text-align: center;">Reporte de cuentas Streaming</h3>';
$html .= '<table border="1" cellpadding="5" cellspacing="0" width="100%">';
$html .= '<thead><tr>';
$html .= '<th style="text-align: center; vertical-align: middle;">ID</th>
    <th style="text-align: center; vertical-align: middle;">Cliente</th>
    <th style="text-align: center; vertical-align: middle;">Plataforma</th>
    <th style="text-align: center; vertical-align: middle;">Correo</th>
    <th style="text-align: center; vertical-align: middle;">Fecha Expiración</th>
    <th style="text-align: center; vertical-align: middle;">Precio</th>
</tr></thead><tbody>';

$total = 0;
foreach ($accounts as $row) {
    $html .= '<tr>';
    $html .= '<td style="text-align: center; vertical-align: middle;">' . htmlspecialchars($row['id']) . '</td>';
    $html .= '<td style="text-align: center; vertical-align: middle;">' . htmlspecialchars($row['client_name']) . '</td>';
    $html .= '<td style="text-align: center; vertical-align: middle;">' . htmlspecialchars($row['platform_name']) . '</td>';
    $html .= '<td style="text-align: center; vertical-align: middle;">' . htmlspecialchars($row['email']) . '</td>';
    $html .= '<td style="text-align: center; vertical-align: middle;">' . htmlspecialchars(formatDateForDisplay($row['expiration_date'])) . '</td>';
    $html .= '<td style="text-align: center; vertical-align: middle;">$' . number_format($row['price'], 2) . '</td>';
    $html .= '</tr>';
    $total += $row['price'];
}

$html .= '<tr>';
$html .= '<td colspan="5" style="text-align: right; vertical-align: middle; font-weight: bold;">Total:</td>';
$html .= '<td style="text-align: center; vertical-align: middle; font-weight: bold;">$' . number_format($total, 2) . '</td>';
$html .= '</tr>';
$html .= '</tbody></table>';

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('letter', 'portrait');
$dompdf->render();
$dompdf->stream('reporte_cuentas.pdf', ['Attachment' => true]);
exit;
