<?php
/* explorador.php (PHP 8.2)
 * Basado en tu base.php (mismo menú/estructura).
 *
 * Carpeta objetivo: "MM-YYYY" (ej: 01-2024) en el MISMO directorio que este archivo.
 * Previews:
 *  - Imágenes: ../timthumb.php
 *  - Audio: <audio>
 *  - Video: <video>
 * Paginación: 50
 * Eliminar: POST + confirm + CSRF + validación básica
 */

include 'sesion.php';
include '../url_amigable.php';
include 'concha.php';

/* =========================
   CONFIG
========================= */
$PER_PAGE     = 50;
$TIMTHUMB_URL = '../timthumb.php'; // como pediste
$BASE_DIR     = __DIR__;           // donde existen 01-2024, 02-2024, etc. (mismo dir)

/* =========================
   SESSION / CSRF / FLASH
========================= */
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
if (empty($_SESSION['csrf_explorador'])) {
    $_SESSION['csrf_explorador'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_explorador'];

$flash = '';
if (!empty($_SESSION['flash_explorador'])) {
    $flash = (string)$_SESSION['flash_explorador'];
    unset($_SESSION['flash_explorador']);
}

/* =========================
   HELPERS
========================= */
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function file_type($name) {
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $img = ['jpg','jpeg','png','gif','webp'];
    $aud = ['mp3','aac','m4a','ogg','wav'];
    $vid = ['mp4','webm','ogv','mov','m4v'];
    if (in_array($ext, $img, true)) return 'image';
    if (in_array($ext, $aud, true)) return 'audio';
    if (in_array($ext, $vid, true)) return 'video';
    return 'other';
}

function human_size($bytes) {
    $bytes = (int)$bytes;
    $u = ['B','KB','MB','GB','TB'];
    $i = 0; $b = (float)$bytes;
    while ($b >= 1024 && $i < count($u)-1) { $b /= 1024; $i++; }
    $s = number_format($b, 2, '.', '');
    $s = rtrim(rtrim($s, '0'), '.');
    return $s.' '.$u[$i];
}

/* =========================
   SELECCIÓN MES/AÑO
========================= */
$mes  = isset($_GET['mes']) ? (int)$_GET['mes'] : (int)date('m');
$anio = isset($_GET['anio']) ? (int)$_GET['anio'] : (int)date('Y');
$mes  = max(1, min(12, $mes));
$anio = max(2000, min(2100, $anio));

$folder = sprintf('%02d-%04d', $mes, $anio);
$folderPath = $BASE_DIR . DIRECTORY_SEPARATOR . $folder;

/* =========================
   ELIMINAR (POST) + REDIRECT
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do']) && $_POST['do'] === 'delete') {

    $mesP  = isset($_POST['mes']) ? (int)$_POST['mes'] : $mes;
    $anioP = isset($_POST['anio']) ? (int)$_POST['anio'] : $anio;
    $pP    = isset($_POST['p']) ? (int)$_POST['p'] : 1;

    $mesP  = max(1, min(12, $mesP));
    $anioP = max(2000, min(2100, $anioP));
    $pP    = max(1, $pP);

    $folderP = sprintf('%02d-%04d', $mesP, $anioP);
    $dirP = $BASE_DIR . DIRECTORY_SEPARATOR . $folderP;

    $token = isset($_POST['csrf']) ? (string)$_POST['csrf'] : '';
    $file  = isset($_POST['file']) ? trim((string)$_POST['file']) : '';

    $msg = '';

    if (!hash_equals($csrf, $token)) {
        $msg = 'Token inválido. Recargá e intentá de nuevo.';
    } elseif (!preg_match('~^(0[1-9]|1[0-2])-\d{4}$~', $folderP)) {
        $msg = 'Carpeta inválida.';
    } elseif ($file === '' || $file !== basename($file) || strpos($file, '..') !== false || strpos($file, '/') !== false || strpos($file, '\\') !== false) {
        $msg = 'Archivo inválido.';
    } elseif (!is_dir($dirP)) {
        $msg = 'La carpeta no existe.';
    } else {
        $target = $dirP . DIRECTORY_SEPARATOR . $file;
        if (!is_file($target)) {
            $msg = 'El archivo ya no existe.';
        } else {
            if (@unlink($target)) {
                $msg = 'Archivo eliminado: ' . $file;
            } else {
                $msg = 'No se pudo eliminar (permisos).';
            }
        }
    }

    $_SESSION['flash_explorador'] = $msg;

    $qs = 'mes='.(int)$mesP.'&anio='.(int)$anioP.'&p='.(int)$pP;
    header('Location: explorador.php?'.$qs, true, 302);
    exit;
}

/* =========================
   PAGINACIÓN + LISTADO
========================= */
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$page = max(1, $page);

$files = [];
if (is_dir($folderPath)) {
    $scan = @scandir($folderPath);
    if (is_array($scan)) {
        foreach ($scan as $f) {
            if ($f === '.' || $f === '..') continue;
            $abs = $folderPath . DIRECTORY_SEPARATOR . $f;
            if (is_file($abs)) {
                $files[] = $f;
            }
        }
    }
}

/* Orden: más nuevo primero (mtime), sin re-llamar filemtime en el sort */
if (!empty($files)) {
    $mt = [];
    foreach ($files as $f) {
        $mt[$f] = @filemtime($folderPath . DIRECTORY_SEPARATOR . $f);
        if (!is_int($mt[$f])) $mt[$f] = 0;
    }
    usort($files, function($a, $b) use ($mt) {
        $tb = $mt[$b] ?? 0;
        $ta = $mt[$a] ?? 0;
        if ($tb === $ta) return strnatcasecmp($a, $b);
        return ($tb < $ta) ? -1 : 1;
    });
}

$total = count($files);
$totalPages = ($total > 0) ? (int)ceil($total / $PER_PAGE) : 1;
if ($page > $totalPages) $page = $totalPages;

$offset = ($page - 1) * $PER_PAGE;
$view = array_slice($files, $offset, $PER_PAGE);

/* URLs para timthumb (mejor absolute) */
$https  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
$scheme = $https ? 'https' : 'http';
$host   = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$scriptDirUrl = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
$baseAbs = $scheme . '://' . $host . ($scriptDirUrl ? $scriptDirUrl : '');

/* Año select */
$yNow = (int)date('Y');
$yearFrom = max(2000, $yNow - 10);
$yearTo   = min(2100, $yNow + 1);

?>
<!DOCTYPE html>
<html lang="es">
<head>
	<meta charset="utf-8">
	<meta name="description" content="Panel de Administracion">
	<meta name="author" content="<?php echo $nombresitio ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title><?php echo $nombresitio ?> - Explorador</title>

  <link href="https://fonts.googleapis.com/css?family=Montserrat:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900&display=swap" rel="stylesheet">
  <link rel="shortcut icon" href="" type="image/x-icon">
	<link rel="apple-touch-icon" href="">

	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" crossorigin="anonymous"></script>
  <script src="../js/jquery.fittext.js"></script>

<script>
$(".tamañoMenu").fitText(1.2, { minFontSize: '14px', maxFontSize: '32px' });
</script>

<style>
  *{ border-radius:0!important; }
  body{
    background-image: url(../fondeux.jpg);
    background-position:top center;
    background-repeat: repeat-x;
    background-color:#EBEBEB;
    height:100%;
  }

  .btn, a, h1, h2, h3, h4, h5, h6, b{
    font-family: 'Montserrat', sans-serif;
  }
  .btn, h1, h2, h3, h4, h5, h6 { font-weight: 600; }

  .btn-primary{
    color:#fff!important;
    background-color:#0066FF;
    border-color:#0066FF;
  }

  .page-header{
    margin:0;
    padding:1em;
    background-color:#0066FF;
    border:0;
    text-align:center;
  }
  .page-header h2{ color:#fff; font-weight:bold; }

  .card-file{
    border:1px solid #e4e4e4;
    background:#fff;
  }
  .thumb{
    width:100%;
    height:180px;
    background:#f5f5f5;
    display:flex;
    align-items:center;
    justify-content:center;
    overflow:hidden;
  }
  .thumb img{ width:100%; height:100%; object-fit:cover; display:block; }
  video{ width:100%; height:180px; object-fit:cover; background:#000; }
  audio{ width:100%; }

  .fname{
    font-size:13px;
    font-weight:700;
    line-height:1.2;
    word-break:break-word;
  }
  .meta{
    font-size:12px;
    color:#555;
  }
  .pager a, .pager span{
    display:inline-block;
    padding:8px 10px;
    border:1px solid #e4e4e4;
    background:#fff;
    color:#0066FF;
    margin-right:6px;
    text-decoration:none;
    font-weight:600;
  }
  .pager .active{
    background:#0066FF;
    color:#fff;
    border-color:#0066FF;
  }
</style>

<script language="javascript">
function ventanaSecundaria (URL){
  window.open(URL,"ventana1","width=550,height=450,scrollbars=NO");
}
</script>

</head>

<body>

<div class="container p-0" style="background-color:#F1F2ED;">
  <?php include 'menu.php'; ?>
</div>

<div style="background-color:#fff;" class="container pt-3">

  <div class="row">
    <div class="col-12 col-lg-12">

      <div class="page-header mb-3">
        <h2 class="m-0">Explorador</h2>
      </div>

      <?php if ($flash !== ''): ?>
        <div class="alert alert-info"><?php echo h($flash); ?></div>
      <?php endif; ?>

      <!-- SELECT MES/AÑO (primera pantalla) -->
      <div class="card-file p-3 mb-3">
        <form method="get" action="explorador.php" class="form-inline">
          <label class="mr-2"><b>Mes</b></label>
          <select name="mes" class="form-control mr-3">
            <?php for ($m=1; $m<=12; $m++): ?>
              <option value="<?php echo (int)$m; ?>" <?php echo ($m===$mes ? 'selected' : ''); ?>>
                <?php echo sprintf('%02d', $m); ?>
              </option>
            <?php endfor; ?>
          </select>

          <label class="mr-2"><b>Año</b></label>
          <select name="anio" class="form-control mr-3">
            <?php for ($y=$yearTo; $y>=$yearFrom; $y--): ?>
              <option value="<?php echo (int)$y; ?>" <?php echo ($y===$anio ? 'selected' : ''); ?>>
                <?php echo (int)$y; ?>
              </option>
            <?php endfor; ?>
          </select>

          <button type="submit" class="btn btn-primary">Explorar</button>

          <div class="ml-3 text-muted" style="font-size:13px;">
            Carpeta: <b><?php echo h($folder); ?></b>
            <?php if (!is_dir($folderPath)): ?>
              (no existe)
            <?php else: ?>
              (<?php echo (int)$total; ?> archivos)
            <?php endif; ?>
          </div>
        </form>
      </div>

      <?php if (!is_dir($folderPath)): ?>
        <div class="card-file p-3">
          No existe la carpeta <b><?php echo h($folder); ?></b> en este directorio.
        </div>
      <?php elseif ($total === 0): ?>
        <div class="card-file p-3">
          No hay archivos dentro de <b><?php echo h($folder); ?></b>.
        </div>
      <?php else: ?>

        <!-- LISTADO -->
        <div class="row">
          <?php foreach ($view as $fname): ?>
            <?php
              $abs = $folderPath . DIRECTORY_SEPARATOR . $fname;
              $type = file_type($fname);
              $size = is_file($abs) ? (int)@filesize($abs) : 0;
              $mtime = is_file($abs) ? (int)@filemtime($abs) : 0;

              $relUrl = $folder . '/' . rawurlencode($fname);
              $absUrl = rtrim($baseAbs, '/') . '/' . $folder . '/' . rawurlencode($fname);

              $thumb = $TIMTHUMB_URL . '?src=' . urlencode($absUrl) . '&w=520&h=360&zc=1&q=90';
            ?>

            <div class="col-12 col-sm-6 col-lg-3 mb-3">
              <div class="card-file">

                <div class="thumb">
                  <?php if ($type === 'image'): ?>
                    <a href="<?php echo h($relUrl); ?>" target="_blank" rel="noopener">
                      <img src="<?php echo h($thumb); ?>" alt="<?php echo h($fname); ?>">
                    </a>
                  <?php elseif ($type === 'audio'): ?>
                    <div style="width:100%; padding:10px;">
                      <audio controls preload="none">
                        <source src="<?php echo h($relUrl); ?>">
                      </audio>
                    </div>
                  <?php elseif ($type === 'video'): ?>
                    <video controls preload="none">
                      <source src="<?php echo h($relUrl); ?>">
                    </video>
                  <?php else: ?>
                    <div class="text-muted" style="font-size:13px; text-align:center;">
                      <i class="fas fa-file" style="font-size:28px; color:#0066FF;"></i>
                    </div>
                  <?php endif; ?>
                </div>

                <div class="p-2">
                  <div class="fname"><?php echo h($fname); ?></div>
                  <div class="meta mt-1">
                    <?php echo h(human_size($size)); ?>
                    <?php if ($mtime): ?> — <?php echo h(date('d/m/Y H:i', $mtime)); ?><?php endif; ?>
                  </div>

                  <div class="d-flex justify-content-between mt-2">
                    <a class="btn btn-sm btn-primary" href="<?php echo h($relUrl); ?>" target="_blank" rel="noopener">
                      Abrir
                    </a>

                    <form method="post" action="explorador.php?mes=<?php echo (int)$mes; ?>&anio=<?php echo (int)$anio; ?>&p=<?php echo (int)$page; ?>"
                          onsubmit="return confirm('¿Eliminar este archivo?\n\n<?php echo h(addslashes($fname)); ?>');">
                      <input type="hidden" name="do" value="delete">
                      <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
                      <input type="hidden" name="mes" value="<?php echo (int)$mes; ?>">
                      <input type="hidden" name="anio" value="<?php echo (int)$anio; ?>">
                      <input type="hidden" name="p" value="<?php echo (int)$page; ?>">
                      <input type="hidden" name="file" value="<?php echo h($fname); ?>">
                      <button type="submit" class="btn btn-sm btn-danger">
                        Eliminar
                      </button>
                    </form>
                  </div>
                </div>

              </div>
            </div>
          <?php endforeach; ?>
        </div>

        <!-- PAGINACIÓN -->
        <?php if ($totalPages > 1): ?>
          <div class="pager mb-4">
            <?php
              $prev = ($page > 1) ? ($page - 1) : 1;
              $next = ($page < $totalPages) ? ($page + 1) : $totalPages;

              $base = 'explorador.php?mes='.(int)$mes.'&anio='.(int)$anio.'&p=';
            ?>
            <a href="<?php echo h($base.$prev); ?>">&laquo;</a>

            <?php
              $startP = max(1, $page - 4);
              $endP   = min($totalPages, $page + 4);

              if ($startP > 1) {
                echo '<a href="'.h($base.'1').'">1</a>';
                if ($startP > 2) echo '<span>...</span>';
              }

              for ($i=$startP; $i<=$endP; $i++) {
                if ($i === $page) echo '<span class="active">'.(int)$i.'</span>';
                else echo '<a href="'.h($base.$i).'">'.(int)$i.'</a>';
              }

              if ($endP < $totalPages) {
                if ($endP < $totalPages-1) echo '<span>...</span>';
                echo '<a href="'.h($base.$totalPages).'">'.(int)$totalPages.'</a>';
              }
            ?>

            <a href="<?php echo h($base.$next); ?>">&raquo;</a>
          </div>
        <?php endif; ?>

      <?php endif; ?>

    </div>
  </div>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.8.1/js/all.js" crossorigin="anonymous"></script>

</body>
</html>