<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['admin_id'])) {
    header('location: ../../');
    exit;
}

require_once __DIR__ . '/../../config/config.php';
require_once dirname(__DIR__, 3) . '/vendor/autoload.php';

function parseReporteDateRangePdf(string $daterange): array
{
    $parts = explode(' - ', $daterange);
    if (count($parts) !== 2) {
        return [null, null];
    }

    $start = DateTime::createFromFormat('d/m/Y H:i:s', trim($parts[0]) . ' 00:00:00');
    $end = DateTime::createFromFormat('d/m/Y H:i:s', trim($parts[1]) . ' 23:59:59');

    if (!$start || !$end) {
        return [null, null];
    }

    return [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')];
}

function h($value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

$daterange = (string)($_REQUEST['daterange'] ?? '');
$category = (int)($_REQUEST['category'] ?? 0);
[$fecha_inicial, $fecha_final] = parseReporteDateRangePdf($daterange);

if (!$fecha_inicial || !$fecha_final) {
    echo "<script>alert('Rango de fechas invalido.')</script>";
    echo "<script>window.close();</script>";
    exit;
}

$where = 'tickets.created_at BETWEEN ? AND ? AND tickets.status_ticket = 1';
$params = [$fecha_inicial, $fecha_final];
$types = 'ss';

if ($category > 0) {
    $where .= ' AND tickets.status_id = ?';
    $params[] = $category;
    $types .= 'i';
}

$sql = "SELECT
        tickets.id,
        tickets.created_at,
        tickets.number_ticket,
        client_user.fullname AS client_fullname,
        client_user.name AS client_name,
        client_user.lastname AS client_lastname,
        status.name AS status_name,
        tipos_requerimientos.name AS categoria_name,
        area.name AS area_name
    FROM tickets
    LEFT JOIN user AS client_user ON client_user.id = tickets.client_id
    LEFT JOIN status ON status.id = tickets.status_id
    LEFT JOIN tipos_requerimientos ON tipos_requerimientos.id = tickets.tipo_requerimiento
    LEFT JOIN area ON area.id = tickets.area
    WHERE $where
    ORDER BY tickets.created_at DESC";

$stmt = mysqli_prepare($con, $sql);
if (!$stmt) {
    echo "<script>alert('No se pudo preparar el reporte.')</script>";
    echo "<script>window.close();</script>";
    exit;
}

mysqli_stmt_bind_param($stmt, $types, ...$params);
mysqli_stmt_execute($stmt);
$query = mysqli_stmt_get_result($stmt);

if (!$query || mysqli_num_rows($query) === 0) {
    echo "<script>alert('No hay Tickets agregados para el rango seleccionado!')</script>";
    echo "<script>window.close();</script>";
    exit;
}

$website = 'Ticketly';
$config = mysqli_query($con, "SELECT val FROM configuration WHERE name = 'website' LIMIT 1");
if ($config && ($rowConfig = mysqli_fetch_assoc($config)) && $rowConfig['val'] !== '') {
    $website = $rowConfig['val'];
}

$rowsHtml = '';
while ($row = mysqli_fetch_assoc($query)) {
    $fullname = trim((string)($row['client_fullname'] ?: trim((string)$row['client_name'] . ' ' . (string)$row['client_lastname'])));
    $createdAt = $row['created_at'] ? date('d/m/Y', strtotime($row['created_at'])) : '';

    $rowsHtml .= '<tr>';
    $rowsHtml .= '<td style="width: 10%; text-align: left">' . h($createdAt) . '</td>';
    $rowsHtml .= '<td style="width: 15%; text-align: right">' . h($row['number_ticket']) . '</td>';
    $rowsHtml .= '<td style="width: 20%; text-align: center">' . h($fullname) . '</td>';
    $rowsHtml .= '<td style="width: 20%; text-align: center">' . h($row['area_name']) . '</td>';
    $rowsHtml .= '<td style="width: 20%; text-align: center">' . h($row['categoria_name']) . '</td>';
    $rowsHtml .= '<td style="width: 15%; text-align: center">' . h($row['status_name']) . '</td>';
    $rowsHtml .= '</tr>';
}
mysqli_stmt_close($stmt);

$content = '
<style type="text/css">
table { vertical-align: top; border-collapse: collapse; }
tr { vertical-align: top; }
td { vertical-align: top; }
table.page_footer { width: 100%; border: none; background-color: white; padding: 2mm; }
</style>
<page backtop="15mm" backbottom="15mm" backleft="15mm" backright="15mm" style="font-size: 12pt; font-family: arial">
    <page_footer>
        <table class="page_footer">
            <tr>
                <td style="width: 50%; text-align: left">Pagina [[page_cu]]/[[page_nb]]</td>
                <td style="width: 50%; text-align: right">&copy; ' . h($website) . ' ' . date('Y') . '</td>
            </tr>
        </table>
    </page_footer>

    <table cellspacing="0" style="width: 100%;">
        <tr>
            <td style="width: 25%; color: #444444;"><h1>' . h($website) . '</h1></td>
            <td style="width: 75%; text-align: right"><h2 style="color: #16a085;">Tickets</h2></td>
        </tr>
    </table>
    <br>
    <table cellspacing="0" style="width: 100%; text-align: left; font-size: 11pt;">
        <tr>
            <td style="width: 50%; text-align: left">Rango: ' . h($daterange) . '</td>
            <td style="width: 50%; text-align: right">Fecha: ' . date('d/m/Y') . '</td>
        </tr>
    </table>
    <br>
    <table cellspacing="0" style="width: 100%; border: solid 1px #16a085; background: #16a085; color: white; text-align: center; font-size: 10pt; padding: 1mm;">
        <tr>
            <th style="width: 10%">FECHA</th>
            <th style="width: 15%">CODIGO</th>
            <th style="width: 20%">EMPLEADO</th>
            <th style="width: 20%">AREA</th>
            <th style="width: 20%">CATEGORIA</th>
            <th style="width: 15%">STATUS</th>
        </tr>
    </table>
    <table border="1" cellspacing="0" style="width: 100%; border: solid 1px #16a085; text-align: center; font-size: 9.5pt; padding: 1mm;">
        ' . $rowsHtml . '
    </table>
</page>';

try {
    $html2pdf = new \Spipu\Html2Pdf\Html2Pdf('P', 'LETTER', 'es', true, 'UTF-8', [0, 0, 0, 0]);
    $html2pdf->pdf->SetDisplayMode('fullpage');
    $html2pdf->writeHTML($content);
    $html2pdf->Output('Tickets.pdf');
} catch (\Spipu\Html2Pdf\Exception\Html2PdfException $e) {
    echo $e;
    exit;
}