<?php
session_start();
include '../includes/session_control.php';
include '../db/db.php';

$idNota = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$idNota) {
    die('ID de nota inválido.');
}

// Directorio donde guardaste las imágenes:
$uploadDir = __DIR__ . "/../archivoDigital/soporteAnticipo/{$idNota}/";

?>
<?php include '../templates/header.php'; ?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Soporte de Anticipo #<?= $idNota ?></h1>

    <?php if (is_dir($uploadDir)):
        // Leemos todos los archivos dentro de la carpeta
        $files = array_diff(scandir($uploadDir), ['.', '..']);
        if (count($files) === 0): ?>
            <div class="alert alert-warning">No hay archivos cargados para este anticipo.</div>
        <?php else: ?>
            <div class="row">
                <?php foreach ($files as $file):
                    $path = htmlspecialchars($uploadDir . $file, ENT_QUOTES);
                    $url  = "/archivoDigital/soporteAnticipo/{$idNota}/" . rawurlencode($file);

                    // Detectar si es imagen o PDF
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                ?>
                    <div class="col-md-3 mb-3 text-center">
                        <?php if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp'])): ?>
                            <a href="<?= $url ?>" target="_blank">
                                <img src="<?= $url ?>"
                                    class="img-fluid img-thumbnail"
                                    style="max-height: 150px;">
                            </a>
                            <p class="mt-1"><?= htmlspecialchars($file, ENT_QUOTES) ?></p>
                        <?php elseif ($ext === 'pdf'): ?>
                            <a href="<?= $url ?>" target="_blank">
                                <i class="fas fa-file-pdf fa-3x text-danger"></i>
                            </a>
                            <p class="mt-1"><?= htmlspecialchars($file, ENT_QUOTES) ?></p>
                        <?php else: ?>
                            <a href="<?= $url ?>" target="_blank">
                                <i class="fas fa-file-alt fa-3x text-secondary"></i>
                            </a>
                            <p class="mt-1"><?= htmlspecialchars($file, ENT_QUOTES) ?></p>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    <?php else: ?>
        <div class="alert alert-warning">No existe carpeta de soporte para este anticipo.</div>
    <?php endif; ?>
</div>

<?php include '../templates/footer.php'; ?>