<?php
/**
 * modules/facturacion/explorador_onedrive.php
 * Explorador de documentos OneDrive — Facturación
 * Navega carpetas del OneDrive clasificadas por instituto.
 */
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../config/onedrive.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/flash.php';
require_once __DIR__ . '/../../includes/OneDriveStorage.php';
requireRol(ROL_FACTURACION);
$idInst = instId();

$CARPETAS = [
    'comprobantes_practicas'   => ['label' => 'Comprobantes Prácticas',  'icon' => 'fa-receipt',          'color' => '#06b6d4'],
    'comprobantes_vinculacion' => ['label' => 'Comprobantes Vinculación','icon' => 'fa-receipt',          'color' => '#6366f1'],
    'documentos_ppp'           => ['label' => 'Documentos PPP',          'icon' => 'fa-file-contract',   'color' => '#0ea5e9'],
    'bitacoras'                => ['label' => 'Bitácoras',               'icon' => 'fa-book-open',        'color' => '#8b5cf6'],
    'fichas_ppp'               => ['label' => 'Fichas PPP',              'icon' => 'fa-id-card',          'color' => '#f59e0b'],
    'informes'                 => ['label' => 'Informes',                'icon' => 'fa-file-lines',       'color' => '#10b981'],
    'actas'                    => ['label' => 'Actas',                   'icon' => 'fa-scroll',           'color' => '#ef4444'],
    'certificados'             => ['label' => 'Certificados',            'icon' => 'fa-certificate',      'color' => '#f97316'],
    'convalidaciones'          => ['label' => 'Convalidaciones',         'icon' => 'fa-rotate',           'color' => '#ec4899'],
    'titulacion'               => ['label' => 'Titulación',              'icon' => 'fa-graduation-cap',   'color' => '#14b8a6'],
    'vinculacion'              => ['label' => 'Vinculación',             'icon' => 'fa-people-group',     'color' => '#84cc16'],
    'solicitudes'              => ['label' => 'Solicitudes',             'icon' => 'fa-envelope-open-text','color'=> '#a78bfa'],
    'documentos_personales'    => ['label' => 'Documentos Personales',   'icon' => 'fa-folder-open',      'color' => '#78716c'],
];

$carpetaSel = $_GET['carpeta'] ?? '';
$subdirSel  = $_GET['subdir']  ?? '';
$busqueda   = trim($_GET['q']  ?? '');
$archivos   = [];
$subdirs    = [];
$errorMsg   = '';

if ($carpetaSel && isset($CARPETAS[$carpetaSel])) {
    try {
        if (!$subdirSel) {
            $subdirs = OneDriveStorage::listSubfolders($carpetaSel, $idInst);
        }
        $archivos = OneDriveStorage::listFolder($carpetaSel, $idInst, $subdirSel ?: null);
        if ($busqueda) {
            $archivos = array_values(array_filter($archivos, fn($a) => stripos($a['name'], $busqueda) !== false));
        }
    } catch (Exception $e) {
        $errorMsg = $e->getMessage();
    }
}

$sbActivo = 'explorador_onedrive';
require_once __DIR__ . '/../../includes/sidebar_facturacion.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Explorador OneDrive — SIGVP</title>
  <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sigvp.css">
  <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-facturacion.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
  <style>
    .exp-wrap { padding: 28px 32px; max-width: 1300px; }
    .exp-header h2 { font-size:1.45rem;font-weight:700;color:#0f172a;margin:0 0 4px; }
    .exp-header p  { color:#64748b;font-size:.875rem;margin:0 0 24px; }
    .exp-grid { display:grid;grid-template-columns:repeat(auto-fill,minmax(165px,1fr));gap:14px;margin-bottom:32px; }
    .exp-folder-card { display:flex;flex-direction:column;align-items:center;gap:8px;padding:18px 12px;
      border:2px solid #e2e8f0;border-radius:12px;cursor:pointer;text-decoration:none;background:#fff;transition:all .18s; }
    .exp-folder-card:hover,.exp-folder-card.active { border-color:var(--fc,#0ea5e9);
      background:color-mix(in srgb,var(--fc,#0ea5e9) 8%,#fff);transform:translateY(-2px);box-shadow:0 4px 16px rgba(0,0,0,.08); }
    .exp-folder-card i { font-size:2rem;color:var(--fc,#0ea5e9); }
    .exp-folder-card span { font-size:.78rem;font-weight:600;color:#334155;text-align:center;line-height:1.3; }
    .exp-breadcrumb { display:flex;align-items:center;gap:8px;background:#f8fafc;border:1px solid #e2e8f0;
      border-radius:8px;padding:10px 16px;margin-bottom:20px;font-size:.875rem; }
    .exp-breadcrumb a { color:#0ea5e9;text-decoration:none; }
    .exp-filters { display:flex;align-items:center;gap:12px;margin-bottom:18px;flex-wrap:wrap; }
    .exp-filters input { border:1px solid #cbd5e1;border-radius:8px;padding:7px 14px;font-size:.875rem;flex:1;min-width:200px; }
    .exp-subdirs { display:flex;flex-wrap:wrap;gap:8px;margin-bottom:20px; }
    .exp-subdirs a { display:inline-flex;align-items:center;gap:6px;padding:5px 14px;border-radius:20px;
      border:1px solid #e2e8f0;background:#f8fafc;font-size:.8rem;color:#475569;text-decoration:none;transition:all .15s; }
    .exp-subdirs a:hover { background:#0ea5e9;color:#fff;border-color:#0ea5e9; }
    .exp-table-wrap { background:#fff;border-radius:12px;border:1px solid #e2e8f0;overflow:hidden; }
    .exp-table { width:100%;border-collapse:collapse;font-size:.875rem; }
    .exp-table thead { background:#f1f5f9; }
    .exp-table th { padding:12px 16px;text-align:left;font-size:.78rem;color:#64748b;font-weight:600;text-transform:uppercase;letter-spacing:.05em; }
    .exp-table td { padding:12px 16px;border-top:1px solid #f1f5f9;color:#334155;vertical-align:middle; }
    .exp-table tr:hover td { background:#f8fafc; }
    .ico-pdf{color:#ef4444} .ico-word{color:#2563eb} .ico-img{color:#f59e0b} .ico-other{color:#94a3b8}
    .exp-size,.exp-date { color:#94a3b8;white-space:nowrap; }
    .exp-btn-ver { display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:6px;
      background:#0ea5e9;color:#fff;font-size:.78rem;text-decoration:none;transition:background .15s; }
    .exp-btn-ver:hover { background:#0284c7;color:#fff; }
    .exp-btn-dl { display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:6px;margin-left:6px;
      background:#f1f5f9;color:#475569;font-size:.78rem;text-decoration:none;border:1px solid #e2e8f0; }
    .exp-btn-dl:hover { background:#e2e8f0; }
    .exp-empty { text-align:center;padding:60px 20px;color:#94a3b8; }
    .exp-empty i { font-size:3rem;margin-bottom:12px;display:block; }
    .exp-alert { background:#fef2f2;border:1px solid #fecaca;color:#dc2626;border-radius:8px;padding:12px 16px;margin-bottom:18px;font-size:.875rem; }
    .exp-count { font-size:.8rem;color:#64748b;margin-bottom:10px; }
  </style>
</head>
<body>
<?php renderSidebar(); ?>
<main class="main-content">
<div class="exp-wrap">

  <div class="exp-header">
    <h2><i class="fa fa-cloud" style="color:#0ea5e9;margin-right:8px;"></i>Explorador OneDrive</h2>
    <p>Documentos almacenados en OneDrive — Instituto activo</p>
  </div>

  <!-- Grid de carpetas -->
  <div class="exp-grid">
    <?php foreach ($CARPETAS as $key => $meta): ?>
      <a href="?carpeta=<?= urlencode($key) ?>"
         class="exp-folder-card <?= $carpetaSel === $key ? 'active' : '' ?>"
         style="--fc:<?= $meta['color'] ?>">
        <i class="fa <?= $meta['icon'] ?>"></i>
        <span><?= $meta['label'] ?></span>
      </a>
    <?php endforeach; ?>
  </div>

  <?php if ($carpetaSel && isset($CARPETAS[$carpetaSel])): ?>

    <!-- Breadcrumb -->
    <div class="exp-breadcrumb">
      <i class="fa fa-cloud" style="color:#0ea5e9;"></i>
      <a href="explorador_onedrive.php">OneDrive</a>
      <span style="color:#94a3b8;">/</span>
      <a href="?carpeta=<?= urlencode($carpetaSel) ?>">
        <i class="fa <?= $CARPETAS[$carpetaSel]['icon'] ?>" style="color:<?= $CARPETAS[$carpetaSel]['color'] ?>;margin-right:4px;"></i>
        <?= htmlspecialchars($CARPETAS[$carpetaSel]['label']) ?>
      </a>
      <?php if ($subdirSel): ?>
        <span style="color:#94a3b8;">/</span>
        <span style="font-weight:600;"><?= htmlspecialchars($subdirSel) ?></span>
      <?php endif; ?>
    </div>

    <?php if ($errorMsg): ?>
      <div class="exp-alert"><i class="fa fa-triangle-exclamation me-2"></i><?= htmlspecialchars($errorMsg) ?></div>
    <?php endif; ?>

    <!-- Subcarpetas -->
    <?php if (!$subdirSel && !empty($subdirs)): ?>
      <div class="exp-subdirs">
        <span style="font-size:.8rem;color:#64748b;align-self:center;"><i class="fa fa-folder"></i> Subcarpetas:</span>
        <?php foreach ($subdirs as $sd): ?>
          <a href="?carpeta=<?= urlencode($carpetaSel) ?>&subdir=<?= urlencode($sd) ?>">
            <i class="fa fa-folder"></i> <?= htmlspecialchars($sd) ?>
          </a>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <!-- Búsqueda -->
    <form method="get" class="exp-filters">
      <input type="hidden" name="carpeta" value="<?= htmlspecialchars($carpetaSel) ?>">
      <?php if ($subdirSel): ?><input type="hidden" name="subdir" value="<?= htmlspecialchars($subdirSel) ?>"><?php endif; ?>
      <input type="text" name="q" placeholder="Buscar por nombre de archivo…" value="<?= htmlspecialchars($busqueda) ?>">
      <button type="submit" class="exp-btn-ver"><i class="fa fa-search"></i> Buscar</button>
      <?php if ($busqueda || $subdirSel): ?>
        <a href="?carpeta=<?= urlencode($carpetaSel) ?>" style="padding:7px 14px;border:1px solid #e2e8f0;border-radius:8px;font-size:.875rem;color:#64748b;text-decoration:none;">
          <i class="fa fa-xmark"></i> Limpiar
        </a>
      <?php endif; ?>
    </form>

    <!-- Tabla -->
    <p class="exp-count"><?= count($archivos) ?> archivo<?= count($archivos) !== 1 ? 's' : '' ?> encontrado<?= count($archivos) !== 1 ? 's' : '' ?></p>

    <div class="exp-table-wrap">
      <?php if (empty($archivos)): ?>
        <div class="exp-empty">
          <i class="fa fa-folder-open"></i>
          <p style="font-size:.95rem;margin:0;">No hay archivos en esta carpeta<?= $busqueda ? ' para "'.htmlspecialchars($busqueda).'"' : '' ?></p>
        </div>
      <?php else: ?>
        <table class="exp-table">
          <thead>
            <tr><th>Archivo</th><th>Tamaño</th><th>Fecha</th><th>Acciones</th></tr>
          </thead>
          <tbody>
            <?php foreach ($archivos as $f):
              $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
              [$icoClass, $icoColor] = match($ext) {
                  'pdf'             => ['fa-file-pdf',   'ico-pdf'],
                  'docx','doc'      => ['fa-file-word',  'ico-word'],
                  'jpg','jpeg','png','webp' => ['fa-file-image','ico-img'],
                  default           => ['fa-file',       'ico-other'],
              };
              $kb = $f['size'] > 0 ? round($f['size']/1024,1).' KB' : '—';
            ?>
            <tr>
              <td><i class="fa <?= $icoClass ?> <?= $icoColor ?>" style="margin-right:6px;"></i><?= htmlspecialchars($f['name']) ?></td>
              <td class="exp-size"><?= $kb ?></td>
              <td class="exp-date"><?= $f['modified'] ?></td>
              <td>
                <?php if ($f['downloadUrl']): ?>
                  <a href="<?= htmlspecialchars($f['downloadUrl']) ?>" target="_blank" class="exp-btn-ver"><i class="fa fa-eye"></i> Ver</a>
                  <a href="<?= htmlspecialchars($f['downloadUrl']) ?>" download="<?= htmlspecialchars($f['name']) ?>" class="exp-btn-dl"><i class="fa fa-download"></i></a>
                <?php elseif ($f['webUrl']): ?>
                  <a href="<?= htmlspecialchars($f['webUrl']) ?>" target="_blank" class="exp-btn-ver"><i class="fa fa-external-link"></i> Abrir</a>
                <?php else: ?>
                  <span style="color:#94a3b8;font-size:.8rem;">Sin enlace</span>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>

  <?php elseif (!$carpetaSel): ?>
    <div class="exp-empty" style="border:1px solid #e2e8f0;border-radius:12px;background:#fff;">
      <i class="fa fa-hand-pointer" style="color:#0ea5e9;"></i>
      <p style="font-size:.95rem;margin:0;color:#64748b;">Selecciona una carpeta arriba para explorar sus documentos</p>
    </div>
  <?php endif; ?>

</div>
</main>
<script src="<?= BASE_URL ?>/assets/js/sigvp.js"></script>
</body>
</html>
