<?php
session_start();
if (!isset($_SESSION['usuario']) || empty($_SESSION['usuario'])) {
  header('Location: ../../index.php'); exit();
}
$usuario = $_SESSION['usuario'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<title>URBANVIEW</title>
<link rel="shortcut icon" href="../../resources/img/logour.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- FontAwesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet" />
<!-- DataTables CSS -->
<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet" />

<style>
html, body { height:100%; margin:0; overflow:hidden; font-family: Arial, Helvetica, sans-serif; }
body { display:flex; flex-direction:column; }
.topbar {
  height:60px; background:#343a40; color:#fff; display:flex; align-items:center; justify-content:space-between;
  padding:0 20px; position:fixed; top:0; left:0; right:0; z-index:1000;
}
.wrapper { display:flex; flex-grow:1; margin-top:60px; height:calc(100vh - 60px); overflow:hidden; }
.sidebar {
  width:250px; background:#343a40; padding:20px; overflow-y:auto; flex-shrink:0; transition:width .3s ease;
}
.sidebar.collapsed { width:80px; }
.sidebar a { color:#fff; text-decoration:none; padding:12px; display:flex; align-items:center; }
.main-content {
  flex-grow:1; height:100%; display:flex; flex-direction:column; margin-left:250px; padding:20px;
  transition:margin-left .3s ease; overflow-y:auto;
}
.sidebar.collapsed ~ .main-content { margin-left:80px; }
.info { display:flex; align-items:center; gap:1rem; }

@media (max-width:768px){
  .sidebar { position:fixed; top:60px; left:0; height:calc(100% - 60px); z-index:999; transform:translateX(-100%); transition:transform .3s ease; width:250px; }
  .sidebar.show { transform:translateX(0); }
  .main-content { margin-left:0 !important; }
  .wrapper { flex-direction:column; }
}

/* Switch visual */
.switch-wrapper { display:flex; justify-content:center; align-items:center; }
.switch-custom { position:relative; display:inline-block; width:70px; height:34px; }
.switch-custom input { opacity:0; width:0; height:0; }
.slider-custom{
  position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0; background:#ccc; transition:.4s; border-radius:34px;
  display:flex; align-items:center; justify-content:space-between; padding:0 10px; font-size:16px; color:#fff;
}
.slider-custom .icon-on, .slider-custom .icon-off { opacity:0; transition:opacity .3s ease; }
input:checked + .slider-custom { background:#28a745; }
input:checked + .slider-custom .icon-on { opacity:1; }
input:checked + .slider-custom .icon-off { opacity:0; }
input:not(:checked) + .slider-custom .icon-off { opacity:1; }
input:not(:checked) + .slider-custom .icon-on { opacity:0; }
</style>
</head>
<body>
<header class="topbar">
  <button class="btn btn-dark" onclick="toggleSidebar()" aria-label="Toggle sidebar">
    <i class="fas fa-bars"></i>
  </button>
  <span>URBANVIEW</span>
  <div class="info">
    <span><?=htmlspecialchars($usuario, ENT_QUOTES, 'UTF-8');?></span>
    <span id="fechaActual"></span>
    <span id="horaActual"></span>
    <button class="btn btn-sm btn-danger" onclick="cerrarSesion(event)">
      <i class="fas fa-sign-out-alt"></i>
    </button>
  </div>
</header>

<div class="wrapper">
  <nav class="sidebar"><?php include "menu.php"; ?></nav>
  <div class="main-content">
    <div class="row mb-3">
      <div class="col-md-3">
        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#agregarVideoModal">
          <i class="fas fa-plus"></i> Agregar Video
        </button>
      </div>
    </div>

    <div class="table-responsive">
      <table id="video" class="table table-striped table-bordered align-middle" style="width:100%">
        <thead class="table-dark">
          <tr>
            <th>ID</th>
            <th>DESCRIPCIÓN</th>
            <th>VIDEO</th>
            <th class="text-center">ACTIVO</th>
            <th class="text-center">ACCIÓN</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal Agregar Video -->
<div class="modal fade" id="agregarVideoModal" tabindex="-1" aria-labelledby="agregarVideoModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="formAgregarVideo" class="modal-content" enctype="multipart/form-data">
      <div class="modal-header">
        <h5 class="modal-title" id="agregarVideoModalLabel">Agregar Nuevo Video</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label for="descripcion" class="form-label">Descripción*</label>
          <input type="text" class="form-control" id="descripcion" name="descripcion" required>
        </div>
        <div class="mb-3">
          <label for="videoFile" class="form-label">Seleccionar Video* (MP4 máx 20MB)</label>
          <input type="file" class="form-control" id="videoFile" name="video" accept="video/mp4" required>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" id="btnGuardarVideo" onclick="guardar()" class="btn btn-primary">
          <i class="fas fa-save"></i> Agregar
        </button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
      </div>
    </form>
  </div>
</div>

<!-- JS: jQuery, Bootstrap, DataTables, SweetAlert -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// ===== Utilidades
function notify(type, title, text) {
  if (window.Swal) Swal.fire({ icon:type, title, text, timer:2000, showConfirmButton:false });
  else alert((title ? title+': ' : '') + (text || ''));
}

// ===== Topbar reloj =====
function actualizarHora() {
  const ahora = new Date();
  const opF = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const opH = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
  const f = document.getElementById('fechaActual'); if (f) f.textContent = ahora.toLocaleDateString('es-ES', opF);
  const h = document.getElementById('horaActual'); if (h) h.textContent = ahora.toLocaleTimeString('es-ES', opH);
}
setInterval(actualizarHora, 1000); actualizarHora();

// ===== Sidebar =====
let sidebar = document.querySelector('.sidebar');
function toggleSidebar(){
  if (!sidebar) return;
  if (window.innerWidth <= 768) sidebar.classList.toggle('show');
  else sidebar.classList.toggle('collapsed');
}
document.addEventListener('click', function(e){
  const toggleBtn = e.target.closest('button[onclick="toggleSidebar()"]');
  if (window.innerWidth <= 768 && !sidebar.contains(e.target) && !toggleBtn) sidebar.classList.remove('show');
});

// ===== Cerrar sesión =====
function cerrarSesion(e){
  if (e) e.preventDefault();
  Swal.fire({ title:'¿Cerrar sesión?', icon:'warning', showCancelButton:true, confirmButtonText:'Sí', cancelButtonText:'No' })
  .then(res=>{
    if (res.isConfirmed) {
      fetch('../../controllers/usuario.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:new URLSearchParams({boton:'cerrar'})
      }).then(r=>{ if (r.ok) location.href='../../index.php'; else throw new Error('Error al cerrar sesión'); })
      .catch(err=> notify('error','Error', err.message));
    }
  });
}

// ===== DataTable =====
let tablaVideos = null;

// init seguro (una vez)
function initTablaVideos() {
  const selector = '#video';

  if ($.fn.DataTable.isDataTable(selector)) {
    tablaVideos = $(selector).DataTable();
    tablaVideos.ajax.reload(null, false);
    return;
  }

  tablaVideos = $(selector).DataTable({
    ajax: {
      url: 'listar_videos.php',
      type: 'GET',
      // anti-cache
      data: function (d) { d._ts = Date.now(); },
      dataSrc: function(json){
        if (json && json.error) Swal.fire('Error', json.error, 'error');
        return (json && Array.isArray(json.data)) ? json.data : [];
      },
      error: function(xhr, status, err){
        console.error('responseText:\n' + xhr.responseText);
        Swal.fire('Error', 'Respuesta inválida del servidor (ver consola).', 'error');
      }
    },
    columns: [
      { data: 'id', visible: false }, // ID oculto
      { data: 'video', className: 'align-middle' },
      { data: 'ruta', className: 'align-middle', render: function(ruta){
          if (!ruta) return '';
          return `
            <video width="180" height="100" controls muted preload="metadata" playsinline>
              <source src="${ruta}" type="video/mp4">
              Tu navegador no soporta video.
            </video>`;
        }
      },
      { data: 'activo', className: 'text-center align-middle', render: function(activo, type, row){
          const checked = +activo === 1 ? 'checked' : '';
          return `
            <div class="switch-wrapper text-center">
              <label class="switch-custom m-0">
                <input type="checkbox" class="toggle-switch" data-id="${row.id}" ${checked}>
                <span class="slider-custom">
                  <span class="icon-off"><i class="fas fa-times"></i></span>
                  <span class="icon-on"><i class="fas fa-check"></i></span>
                </span>
              </label>
            </div>`;
        }
      },
      { data: null, orderable: false, searchable: false, className: 'text-center align-middle',
        render: function(data, type, row){
          return `
            <button class="btn btn-danger btn-sm btn-eliminar" data-id="${row.id}">
              <i class="fa fa-trash"></i>
            </button>`;
        }
      }
    ],
    order: [[0, 'desc']], // por ID DESC
    language: { url: 'https://cdn.datatables.net/plug-ins/1.13.4/i18n/es-ES.json' }
  });

  // Pausar videos al paginar/redibujar
  $(selector).on('page.dt draw.dt', function(){
    $(selector + ' video').each(function(){ try{ this.pause(); }catch(e){} });
  });
}

// cargar tabla
$(document).ready(function () { initTablaVideos(); });

// recarga helper
function despuesDeGuardar() { if (tablaVideos) tablaVideos.ajax.reload(null, false); }

// ===== Subir video =====
function guardar(){
  const form = document.getElementById('formAgregarVideo');
  const btn  = document.getElementById('btnGuardarVideo');
  if (!form) return notify('error','Error','No se encontró el formulario');

  const inputDesc = document.getElementById('descripcion');
  const desc = (inputDesc?.value || '').trim();
  if (!desc) { Swal.fire('Atención', 'La descripción es obligatoria.', 'warning'); inputDesc?.focus(); return; }

  // Asegurar que no esté disabled y forzar el valor en FD
  if (inputDesc && inputDesc.disabled) inputDesc.disabled = false;

  const fd = new FormData(form);
  fd.set('descripcion', desc);

  btn.disabled = true; btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Subiendo...';

  $.ajax({
    url:'subir_video.php',
    type:'POST',
    data:fd,
    processData:false,
    contentType:false,
    cache:false,
    dataType:'json'
  }).done(function(r){
    notify('success','Éxito', r.message || 'Video agregado correctamente');
    form.reset();
    const modalEl = document.getElementById('agregarVideoModal');
    if (modalEl) (bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl)).hide();
    despuesDeGuardar();
  }).fail(function(xhr){
    let msg = xhr.statusText;
    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e){}
    Swal.fire('Error', msg || 'No se pudo subir el video', 'error');
  }).always(function(){
    btn.disabled = false; btn.innerHTML = '<i class="fas fa-save"></i> Agregar';
  });
}

// ===== Eliminar =====
$(document).on('click', '.btn-eliminar', function(){
  const id = $(this).data('id');
  Swal.fire({
    title:'¿Estás segura?',
    text:'Esta acción eliminará el video permanentemente.',
    icon:'warning', showCancelButton:true, confirmButtonText:'Sí, eliminar', cancelButtonText:'Cancelar'
  }).then((res)=>{
    if (res.isConfirmed) {
      $.post('eliminar_video.php', { id }, function(response){
        if (response && response.success) {
          notify('success','Eliminado', response.message || 'El video fue eliminado.');
          if (tablaVideos) tablaVideos.ajax.reload(null, false);
        } else {
          notify('error','Error', (response && response.message) ? response.message : 'No se pudo eliminar.');
        }
      }, 'json').fail(function(xhr){
        let msg = xhr.statusText;
        try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e){}
        notify('error','Error', msg);
      });
    }
  });
});

// ===== Toggle Activo =====
$(document).on('change', '.toggle-switch', function(){
  const cb = $(this);
  const id = cb.data('id');
  const activa = cb.is(':checked') ? 1 : 0;

  $.ajax({
    url:'actualizar_estado_video.php',
    method:'POST',
    data:{ id, activa },
    dataType:'json'
  }).done(function(resp){
    if (!resp || resp.success !== true) {
      notify('warning','Atención', (resp && resp.message) ? resp.message : 'No se pudo actualizar.');
      cb.prop('checked', !activa);
    }
  }).fail(function(xhr){
    let msg = xhr.statusText;
    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e){}
    notify('error','Error', msg);
    cb.prop('checked', !activa);
  });
});
</script>
</body>
</html>
