<?php
// index.php modernizado para SGO (Bootstrap 5)
declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');

if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php");
  exit();
}

$usuario = $_SESSION['usuario'] ?? 'Invitado';
$permiso = (int)($_SESSION['permiso'] ?? 0);

require_once __DIR__ . '/conex.php';
?>
<?php include 'partials/header.php'; ?>
<body>
<div class="container-fluid">
  <div class="row">

    <!-- Sidebar -->
    <?php include 'partials/menu.php'; ?>

    <!-- Contenido principal -->
    <main class="col-md-9 ms-sm-auto col-lg-10 px-2">
      <!-- Topbar -->
      <?php include 'partials/topbar.php'; ?>

      <!-- Card principal -->
      <div class="card border-0 shadow-sm mt-2">
        <div class="card-header d-flex align-items-center justify-content-between py-2">
          <h6 class="mb-0">Empresas</h6>
          <button type="button" class="btn btn-success btn-sm" onclick="abrirModalCrear()">
            Agregar Empresa
          </button>
        </div>

        <div class="card-body p-2">
          <div class="table-responsive">
            <table id="cliente" class="table table-sm table-hover align-middle mb-0 w-100">
              <thead class="table-light">
                <tr>
                  <th>RUC</th>
                  <th>Razón social</th>
                  <th>Alias</th>
                  <th>Servicios</th>
                  <th>Estado</th>
                  <th class="text-center">Acciones</th>
                </tr>
              </thead>
              <tbody><!-- filas por AJAX --></tbody>
            </table>
          </div>
        </div>
      </div>
      <!-- /Card principal -->
    </main>
  </div>
</div>

<?php include 'partials/footer.php'; ?>

<!-- Modal: Crear/Editar empresa -->
<div class="modal fade" id="agregar_empresa" tabindex="-1" aria-hidden="true" aria-labelledby="agregarEmpresaLbl">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header py-2">
        <h5 class="modal-title" id="agregarEmpresaLbl">Agregar nueva empresa</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>

      <form id="formEmpresa" class="needs-validation" novalidate>
        <input type="hidden" id="idempresa" name="idempresa" value="">
        <div class="modal-body">
          <div class="row g-2">
            <div class="col-md-4">
              <label for="ruc" class="form-label">RUC <span class="text-danger">*</span></label>
              <input type="text" class="form-control" id="ruc" name="ruc" maxlength="13" inputmode="numeric" required>
              <div class="invalid-feedback">Ingresa un RUC válido de 13 dígitos.</div>
            </div>

            <div class="col-md-4">
              <label for="razon_social" class="form-label">Razón social <span class="text-danger">*</span></label>
              <input type="text" class="form-control" id="razon_social" name="razon_social" required>
              <div class="invalid-feedback">Este campo es obligatorio.</div>
            </div>

            <div class="col-md-4">
              <label for="alias" class="form-label">Alias <span class="text-danger">*</span></label>
              <input type="text" class="form-control" id="alias" name="alias" required>
              <div class="invalid-feedback">Este campo es obligatorio.</div>
            </div>

            <!-- Switch Servicios con etiqueta dinámica Sí/No -->
            <div class="col-12">
              <div class="form-check form-switch mt-2">
                <input class="form-check-input" type="checkbox" id="servicios" name="servicios" value="1">
                <label class="form-check-label" for="servicios" id="lblServicios">No</label>
              </div>
            </div>

            <!-- Switch Estado -->
            <div class="col-12">
              <div class="form-check form-switch mt-2">
                <input class="form-check-input" type="checkbox" id="estado" name="estado" checked>
                <label class="form-check-label" for="estado">Activo</label>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer py-2">
          <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" id="btnGuardarEmpresa" class="btn btn-success btn-sm">
            <span class="spinner-border spinner-border-sm me-1 d-none" role="status" aria-hidden="true"></span>
            <span class="btnText">Guardar</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// ====== DataTable ======
document.addEventListener('DOMContentLoaded', function () {
  if (!(window.jQuery && $.fn.DataTable)) return;

  $('#cliente').DataTable({
    processing: true,
    serverSide: true,
    responsive: true,
    autoWidth: false,
    pageLength: 10,
    lengthMenu: [10, 25, 50, 100],
    ajax: { url: 'api/empresas_listar.php', type: 'GET' },
    columns: [
      { data: 'ruc' },
      { data: 'razon_social' },
      { data: 'alias' },

      // Servicios como switch editable
      {
        data: null,
        render: function (row) {
          const checked = String(row.servicios) === '1' ? 'checked' : '';
          return `
            <div class="form-check form-switch m-0" title="${checked ? 'Sí' : 'No'}">
              <input type="checkbox" class="form-check-input servicios-switch" data-id="${row.idempresa}" ${checked} />
            </div>`;
        },
        className: 'text-start',
        orderable: false,
        searchable: false
      },

      // Estado como switch editable
      {
        data: null,
        render: function (row) {
          const checked = String(row.estado) === '1' ? 'checked' : '';
          return `
            <div class="form-check form-switch m-0" title="${checked ? 'Activo' : 'Inactivo'}">
              <input type="checkbox" class="form-check-input empresa-switch" data-id="${row.idempresa}" ${checked} />
            </div>`;
        },
        className: 'text-start',
        orderable: false,
        searchable: false
      },

      {
        data: 'idempresa',
        orderable: false,
        searchable: false,
        className: 'text-center',
        render: function(id){
          return `
            <div class="btn-group btn-group-sm" role="group">
              <button class="btn btn-outline-primary" onclick="verEmpresa(${id})" title="Ver"><i class="fa-regular fa-eye"></i></button>
              <button class="btn btn-outline-warning" onclick="editarEmpresa(${id})" title="Editar"><i class="fa-regular fa-pen-to-square"></i></button>
              <button class="btn btn-outline-danger" onclick="eliminarEmpresa(${id})" title="Eliminar"><i class="fa-regular fa-trash-can"></i></button>
            </div>`;
        }
      }
    ],
    language: {
      processing:"Procesando...", search:"Buscar:", lengthMenu:"Mostrar _MENU_",
      info:"Mostrando _START_ a _END_ de _TOTAL_", infoEmpty:"Mostrando 0 a 0 de 0",
      infoFiltered:"(filtrado de _MAX_ en total)", loadingRecords:"Cargando...",
      zeroRecords:"No se encontraron resultados", emptyTable:"Sin datos disponibles",
      paginate:{ first:"Primero", previous:"Anterior", next:"Siguiente", last:"Último" }
    },
    order: [[1, 'asc']],
    rowCallback: function(row, data){
      if (String(data.estado) !== '1') row.classList.add('table-secondary','opacity-75');
      else row.classList.remove('table-secondary','opacity-75');
    }
  });

  // Label dinámico Sí/No del switch Servicios en el modal
  const swServicios = document.getElementById('servicios');
  const lblServicios = document.getElementById('lblServicios');
  lblServicios.textContent = swServicios.checked ? 'Sí' : 'No';
  swServicios.addEventListener('change', () => {
    lblServicios.textContent = swServicios.checked ? 'Sí' : 'No';
  });
});

// ====== Acciones (stubs de ver) ======
function verEmpresa(id){ window.Swal ? Swal.fire('Ver', 'ID: '+id, 'info') : alert('Ver ID: '+id); }

// ====== Toggles en la tabla ======
document.addEventListener('change', async (ev)=>{
  const el = ev.target;

  // Toggle ESTADO
  if (el.classList.contains('empresa-switch')) {
    const id  = el.getAttribute('data-id');
    const val = el.checked ? '1' : '0';
    el.disabled = true;
    try {
      const fd = new FormData();
      fd.set('idempresa', id);
      fd.set('estado', val);
      const r = await fetch('api/empresa_toggle_estado.php', {
        method: 'POST', body: fd, headers: {'X-Requested-With':'XMLHttpRequest'}
      });
      const j = await r.json();
      if(!r.ok || !j.success){
        el.checked = !el.checked;
        const msg = j?.message || 'No se pudo actualizar el estado';
        return window.Swal ? Swal.fire('Error', msg, 'error') : alert(msg);
      }
      if (window.jQuery && $.fn.DataTable) $('#cliente').DataTable().ajax.reload(null,false);
      if (window.Swal) Swal.fire({toast:true, position:'top-end', icon:'success', title:'Estado actualizado', showConfirmButton:false, timer:1200});
    } catch (e) {
      console.error(e);
      el.checked = !el.checked;
      window.Swal ? Swal.fire('Error','Error de red o servidor','error') : alert('Error de red o servidor');
    } finally {
      el.disabled = false;
    }
  }

  // Toggle SERVICIOS
  if (el.classList.contains('servicios-switch')) {
    const id  = el.getAttribute('data-id');
    const val = el.checked ? '1' : '0';
    el.disabled = true;
    try {
      const fd = new FormData();
      fd.set('idempresa', id);
      fd.set('servicios', val);
      const r = await fetch('api/empresa_toggle_servicios.php', {
        method: 'POST', body: fd, headers: {'X-Requested-With':'XMLHttpRequest'}
      });
      const j = await r.json();
      if(!r.ok || !j.success){
        el.checked = !el.checked;
        const msg = j?.message || 'No se pudo actualizar Servicios';
        return window.Swal ? Swal.fire('Error', msg, 'error') : alert(msg);
      }
      if (window.jQuery && $.fn.DataTable) $('#cliente').DataTable().ajax.reload(null,false);
      if (window.Swal) Swal.fire({toast:true, position:'top-end', icon:'success', title:'Servicios actualizado', showConfirmButton:false, timer:1200});
    } catch (e) {
      console.error(e);
      el.checked = !el.checked;
      window.Swal ? Swal.fire('Error','Error de red o servidor','error') : alert('Error de red o servidor');
    } finally {
      el.disabled = false;
    }
  }
});

// ====== Modal helpers ======
function validarRUC(r){ return /^\d{13}$/.test(r); }

function abrirModalCrear(){
  document.getElementById('agregarEmpresaLbl').textContent = 'Agregar nueva empresa';
  document.querySelector('#btnGuardarEmpresa .btnText').textContent = 'Guardar';
  const form = document.getElementById('formEmpresa');
  form.reset();
  form.classList.remove('was-validated');
  document.getElementById('idempresa').value = '';
  document.getElementById('estado').checked = true;
  document.getElementById('servicios').checked = false;
  document.getElementById('lblServicios').textContent = 'No';
  bootstrap.Modal.getOrCreateInstance('#agregar_empresa').show();
}

function abrirModalEditar(){
  document.getElementById('agregarEmpresaLbl').textContent = 'Editar empresa';
  document.querySelector('#btnGuardarEmpresa .btnText').textContent = 'Actualizar';
  document.getElementById('formEmpresa').classList.remove('was-validated');
  bootstrap.Modal.getOrCreateInstance('#agregar_empresa').show();
}

function cerrarModalEmpresa(){
  const modal = bootstrap.Modal.getInstance('#agregar_empresa');
  if (modal) modal.hide();
}
document.getElementById('agregar_empresa').addEventListener('hidden.bs.modal', function () {
  document.body.classList.remove('modal-open');
  document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
});

// Cargar y editar
async function editarEmpresa(id){
  try{
    const r = await fetch('api/empresa_obtener.php?idempresa='+encodeURIComponent(id));
    const j = await r.json();
    if(!r.ok || !j.success){
      const msg = j?.message || 'No se pudo obtener la empresa';
      return window.Swal ? Swal.fire('Error', msg, 'error') : alert(msg);
    }
    const e = j.data;
    document.getElementById('idempresa').value = e.idempresa ?? '';
    document.getElementById('ruc').value = e.ruc ?? '';
    document.getElementById('razon_social').value = e.razon_social ?? '';
    document.getElementById('alias').value = e.alias ?? '';
    document.getElementById('servicios').checked = String(e.servicios) === '1';
    document.getElementById('lblServicios').textContent = document.getElementById('servicios').checked ? 'Sí' : 'No';
    document.getElementById('estado').checked = String(e.estado) === '1';
    abrirModalEditar();
  }catch(err){
    console.error(err);
    window.Swal ? Swal.fire('Error', 'Error de red o servidor', 'error') : alert('Error de red o servidor');
  }
}

// Eliminar (soft por defecto; hard opcional)
function eliminarEmpresa(id){
  const doDelete = async (hard=false)=>{
    try{
      const fd = new FormData();
      fd.set('idempresa', String(id));
      if(hard) fd.set('hard','1');
      const r = await fetch('api/empresa_eliminar.php',{ method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
      const j = await r.json();
      if(!r.ok || !j.success){
        const msg = j?.message || 'No se pudo eliminar';
        return window.Swal ? Swal.fire('Error', msg, 'error') : alert(msg);
      }
      if (window.jQuery && $.fn.DataTable) $('#cliente').DataTable().ajax.reload(null,false);
      window.Swal ? Swal.fire('Listo', j.message || 'Operación realizada', 'success') : alert('Operación realizada');
    }catch(err){
      console.error(err);
      window.Swal ? Swal.fire('Error', 'Error de red o servidor', 'error') : alert('Error de red o servidor');
    }
  };

  if (window.Swal) {
    Swal.fire({
      title: '¿Eliminar empresa?',
      html: 'Por defecto se <b>desactiva</b> (soft delete).',
      icon: 'warning',
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: 'Desactivar',
      denyButtonText: 'Eliminar definitivamente',
      cancelButtonText: 'Cancelar'
    }).then(res=>{
      if(res.isConfirmed) doDelete(false);
      else if(res.isDenied) doDelete(true);
    });
  } else {
    if(confirm('Desactivar (OK) o Cancelar.')) doDelete(false);
  }
}

// Submit crear/actualizar
document.getElementById('formEmpresa').addEventListener('submit', async (e)=>{
  e.preventDefault();
  const f = e.currentTarget;
  f.classList.add('was-validated');
  const ruc = (document.getElementById('ruc').value||'').trim();
  if(!f.checkValidity() || !validarRUC(ruc)){
    if(!/^\d{13}$/.test(ruc)) document.getElementById('ruc').classList.add('is-invalid');
    return;
  } else {
    document.getElementById('ruc').classList.remove('is-invalid');
  }

  const id = (document.getElementById('idempresa').value||'').trim();
  const url = id ? 'api/empresa_actualizar.php' : 'api/empresa_crear.php';

  const btn = document.getElementById('btnGuardarEmpresa');
  const spn = btn.querySelector('.spinner-border');
  btn.disabled = true; spn.classList.remove('d-none');

  try{
    const fd = new FormData(f);
    fd.set('estado', document.getElementById('estado').checked ? '1' : '0');
    fd.set('servicios', document.getElementById('servicios').checked ? '1' : '0');
    const r = await fetch(url, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    const j = await r.json();
    if(!r.ok || !j.success){
      const msg = j?.message || 'No se pudo guardar';
      return window.Swal ? Swal.fire('Error', msg, 'error') : alert(msg);
    }
    cerrarModalEmpresa();
    if (window.jQuery && $.fn.DataTable) $('#cliente').DataTable().ajax.reload(null,false);
    window.Swal ? Swal.fire('Listo', j.message || 'Guardado', 'success') : alert('Guardado');
  }catch(err){
    console.error(err);
    window.Swal ? Swal.fire('Error', 'Error de red o servidor', 'error') : alert('Error de red o servidor');
  }finally{
    btn.disabled = false; spn.classList.add('d-none');
  }
});
</script>

<style>
  main { font-size: 0.95rem; }
  .card-header h6 { font-weight: 600; }
  .form-switch .form-check-input { cursor: pointer; }
</style>
</body>
</html>
