<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Proveedores', 'proveedores');
?>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<script src="assets/js/sweetalert2.min.js"></script>
<style>
.pr-container { max-width: 1400px; margin: 0 auto; padding: 2rem; }
.pr-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 2rem; }
.pr-header h1 { font-family: 'League Spartan', sans-serif; font-size: 1.85rem; font-weight: 700; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 0.75rem; }

.pr-card { 
  background: var(--surface) !important; 
  border: 1px solid var(--border) !important; 
  border-radius: var(--radius) !important; 
  box-shadow: var(--shadow) !important;
  overflow: hidden; 
}
.pr-toolbar { 
  padding: 1.25rem 1.5rem; 
  border-bottom: 1px solid var(--border); 
  display: flex; 
  gap: 1.5rem; 
  align-items: center; 
  flex-wrap: wrap; 
  background: rgba(2, 14, 23, 0.4);
}
.pr-search { position: relative; flex: 1; min-width: 250px; }
.pr-search i { position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-secondary); font-size: 0.95rem; }
.pr-search input { 
  width: 100%; 
  padding: 0.75rem 1rem 0.75rem 2.5rem !important; 
  border-radius: var(--radius-sm) !important; 
  border: 1px solid var(--border) !important; 
  background: var(--surface-elevated) !important; 
  font-size: 0.875rem; 
  color: var(--text-primary) !important; 
  box-sizing: border-box; 
  transition: all var(--transition) !important;
}
.pr-search input:focus { 
  outline: none; 
  border-color: var(--primary-light) !important; 
  box-shadow: var(--focus-ring) !important;
  background: var(--surface) !important;
}

.pr-table-wrap { overflow-x: auto; }
.pr-table-wrap table { width: 100%; border-collapse: collapse; min-width: 700px; }
.pr-table-wrap th { 
  background: var(--surface-elevated) !important;
  padding: 1rem 1.25rem !important; 
  font-size: 0.75rem; 
  font-weight: 700; 
  text-transform: uppercase; 
  letter-spacing: 0.05em; 
  color: var(--text-light) !important; 
  border-bottom: 2px solid var(--border) !important; 
  text-align: left; 
  white-space: nowrap; 
}
.pr-table-wrap td { 
  padding: 1rem 1.25rem !important; 
  font-size: 0.875rem; 
  border-bottom: 1px solid var(--border-light) !important; 
  vertical-align: middle; 
  color: var(--text-primary) !important;
}
.pr-table-wrap tr {
  transition: background-color var(--transition);
}
.pr-table-wrap tr:hover { 
  background: var(--surface-hover) !important; 
}

.empty-state { text-align: center; padding: 4rem 2rem; color: var(--text-secondary); }
.empty-state i { font-size: 3.5rem; opacity: 0.3; margin-bottom: 1rem; display: block; color: var(--accent-color); }

.badge-pr { 
  display: inline-flex; 
  padding: 0.25rem 0.65rem; 
  border-radius: 6px; 
  font-size: 0.7rem; 
  font-weight: 700; 
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.badge-pr.activo { 
  background: rgba(34, 197, 94, 0.1) !important; 
  color: var(--success) !important; 
  border: 1px solid rgba(34, 197, 94, 0.2) !important;
}
.badge-pr.inactivo { 
  background: var(--surface-hover) !important; 
  color: var(--text-light) !important; 
  border: 1px solid var(--border) !important;
}

/* Modals */
.modal-overlay { 
  position: fixed; 
  inset: 0; 
  z-index: 1000; 
  background: rgba(2, 6, 17, 0.8) !important; 
  display: none;
  align-items: center; 
  justify-content: center; 
  animation: fadeIn var(--transition) ease-out;
}
.modal-overlay.open { display: flex; }
.modal-content { 
  background: var(--surface-elevated) !important; 
  border: 1px solid var(--border) !important; 
  border-radius: var(--radius-lg) !important; 
  width: 95%; 
  max-width: 540px; 
  max-height: 90vh; 
  overflow-y: auto; 
  padding: 0 !important; 
  box-shadow: var(--shadow-xl) !important; 
}
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--border); }
.modal-header h3 { font-family: 'League Spartan', sans-serif; font-size: 1.35rem; font-weight: 700; margin: 0; color: var(--text-primary); }
.modal-close { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: var(--text-light); padding: 0.25rem; line-height: 1; transition: color var(--transition); }
.modal-close:hover { color: var(--text-primary); }

.modal-body { padding: 1.5rem; }

.form-group { margin-bottom: 1.25rem; display: flex; flex-direction: column; gap: 0.35rem; }
.form-group label { font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; letter-spacing: 0.05em; display: block; }
.form-group input, .form-group textarea { 
  width: 100%; 
  padding: 0.65rem 0.85rem !important; 
  border-radius: var(--radius-sm) !important; 
  border: 1px solid var(--border) !important; 
  background: var(--surface) !important; 
  color: var(--text-primary) !important; 
  font-size: 0.875rem; 
  box-sizing: border-box; 
  transition: all var(--transition) !important;
}
.form-group input:focus, .form-group textarea:focus { 
  outline: none; 
  border-color: var(--primary-light) !important; 
  box-shadow: var(--focus-ring) !important;
}
.form-group textarea { resize: vertical; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }

.modal-footer { display: flex; gap: 0.75rem; padding: 1.25rem 1.5rem; border-top: 1px solid var(--border); }
.modal-footer button { flex: 1; }

/* Buttons styling alignment */
.btn-pr { 
  display: inline-flex; 
  align-items: center; 
  justify-content: center; 
  gap: 0.5rem; 
  padding: 0.6rem 1.25rem; 
  font-weight: 600; 
  font-size: 0.875rem; 
  border-radius: var(--radius-sm); 
  border: none; 
  cursor: pointer; 
  transition: all var(--transition); 
  text-decoration: none; 
}
.btn-pr-primary { 
  background: var(--accent-color) !important; 
  color: #0B0119 !important; 
  box-shadow: var(--shadow) !important;
}
.btn-pr-primary:hover { 
  transform: translateY(-1px); 
  box-shadow: var(--shadow-md) !important;
  opacity: 0.9;
}
.btn-pr-secondary { 
  background: var(--surface) !important; 
  border: 1px solid var(--border) !important; 
  color: var(--text-primary) !important; 
}
.btn-pr-secondary:hover { 
  background: var(--surface-hover) !important; 
}
.btn-pr-sm { 
  padding: 0.35rem 0.75rem; 
  font-size: 0.75rem; 
  border-radius: var(--radius-sm); 
}
@media (max-width: 768px) { .pr-container { padding: 1rem; } .form-row { grid-template-columns: 1fr; } }
</style>

<div class="pr-container">
  <div class="pr-header">
    <h1><i class="bi bi-building"></i> Proveedores</h1>
    <button class="btn-pr btn-pr-primary" onclick="abrirModal()"><i class="bi bi-plus-lg"></i> Nuevo Proveedor</button>
  </div>

  <div class="pr-card">
    <div class="pr-toolbar">
      <div class="pr-search">
        <i class="bi bi-search"></i>
        <input type="text" id="searchInput" placeholder="Buscar por nombre, contacto o teléfono..." oninput="cargarProveedores()">
      </div>
      <label style="display:flex;align-items:center;gap:0.5rem;font-size:0.8rem;color:var(--text-light);cursor:pointer">
        <input type="checkbox" id="showInactive" onchange="cargarProveedores()" style="width:1.1rem;height:1.1rem;accent-color:var(--accent-color)">
        Ver inactivos
      </label>
    </div>

    <div id="loader" style="display:none;text-align:center;padding:3rem"><i class="bi bi-arrow-clockwise" style="font-size:1.55rem;animation:spin 1s linear infinite;display:inline-block"></i></div>
    <div id="tableContainer" class="pr-table-wrap">
      <table>
        <thead><tr>
          <th>Proveedor</th><th>Contacto</th><th>Teléfono</th><th>Email</th><th>Crédito (Días)</th><th>Entrega (Días)</th><th style="text-align:center">Estado</th><th style="text-align:center">Acción</th>
        </tr></thead>
        <tbody id="proveedoresBody"></tbody>
      </table>
    </div>
    <div id="emptyState" style="display:none" class="empty-state">
      <i class="bi bi-inbox"></i>
      <p>No se encontraron proveedores</p>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal-overlay" id="modalProveedor">
  <div class="modal-content">
    <div class="modal-header">
      <h3 id="modalTitle">Nuevo Proveedor</h3>
      <button class="modal-close" onclick="cerrarModal()">&times;</button>
    </div>
    <input type="hidden" id="editId" value="">
    
    <div class="modal-body">
      <div class="form-group">
        <label>Nombre del Proveedor *</label>
        <input type="text" id="f_nombre" placeholder="Nombre del proveedor">
      </div>
      <div class="form-group">
        <label>Persona de Contacto</label>
        <input type="text" id="f_contacto" placeholder="Nombre del contacto">
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Teléfono</label>
          <input type="text" id="f_telefono" placeholder="Teléfono">
        </div>
        <div class="form-group">
          <label>Email</label>
          <input type="email" id="f_email" placeholder="correo@ejemplo.com">
        </div>
      </div>
      <div class="form-group">
        <label>Dirección</label>
        <textarea id="f_direccion" rows="2" placeholder="Dirección del proveedor"></textarea>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Días de Crédito</label>
          <input type="number" id="f_dias_credito" value="0" min="0">
        </div>
        <div class="form-group">
          <label>Días de Entrega</label>
          <input type="number" id="f_dias_entrega" value="0" min="0">
        </div>
      </div>
    </div>
    
    <div class="modal-footer">
      <button class="btn-pr btn-pr-primary" onclick="guardarProveedor()"><i class="bi bi-check2"></i> Guardar</button>
      <button class="btn-pr btn-pr-secondary" onclick="cerrarModal()">Cancelar</button>
    </div>
  </div>
</div>

<script>
let proveedoresData = [];

async function cargarProveedores() {
  const search = document.getElementById('searchInput').value.trim();
  const activo = document.getElementById('showInactive').checked ? 0 : 1;
  document.getElementById('loader').style.display = 'block';
  document.getElementById('tableContainer').style.display = 'none';
  document.getElementById('emptyState').style.display = 'none';
  try {
    const res = await fetch(`api/proveedores/listar.php?search=${encodeURIComponent(search)}&activo=${activo}`);
    const d = await res.json();
    document.getElementById('loader').style.display = 'none';
    proveedoresData = d.data || [];
    if (d.success && proveedoresData.length > 0) {
      const tbody = document.getElementById('proveedoresBody');
      tbody.innerHTML = proveedoresData.map(p => {
        const badge = p.activo == 1
          ? '<span class="badge-pr activo">ACTIVO</span>'
          : '<span class="badge-pr inactivo">INACTIVO</span>';
        return `<tr>
          <td><strong>${esc(p.nombre)}</strong></td>
          <td style="color:var(--text-light)">${esc(p.contacto_nombre || '-')}</td>
          <td style="color:var(--text-light)">${esc(p.telefono || '-')}</td>
          <td style="color:var(--text-light); font-family: monospace;">${esc(p.email || '-')}</td>
          <td style="font-weight:700;color:#f59e0b;font-family: monospace;">${p.dias_credito || 0}</td>
          <td style="color:var(--text-light);font-family: monospace;">${p.dias_entrega || 0}</td>
          <td style="text-align:center">${badge}</td>
          <td style="text-align:center;white-space:nowrap">
            <button onclick="editarProveedor(${p.id})" class="btn-pr btn-pr-secondary btn-pr-sm" title="Editar"><i class="bi bi-pencil"></i></button>
            <button onclick="eliminarProveedor(${p.id},'${esc(p.nombre)}')" class="btn-pr btn-pr-sm" style="background:rgba(239,68,68,0.1) !important;color:#ef4444 !important;border:1px solid rgba(239,68,68,0.2) !important" title="Desactivar"><i class="bi bi-trash"></i></button>
          </td>
        </tr>`;
      }).join('');
      document.getElementById('tableContainer').style.display = 'block';
    } else {
      document.getElementById('emptyState').style.display = 'block';
    }
  } catch(e) {
    document.getElementById('loader').style.display = 'none';
    document.getElementById('emptyState').style.display = 'block';
    console.error(e);
  }
}

function abrirModal(p) {
  document.getElementById('editId').value = p ? p.id : '';
  document.getElementById('modalTitle').textContent = p ? 'Editar Proveedor' : 'Nuevo Proveedor';
  document.getElementById('f_nombre').value = p ? p.nombre : '';
  document.getElementById('f_contacto').value = p ? (p.contacto_nombre||'') : '';
  document.getElementById('f_telefono').value = p ? (p.telefono||'') : '';
  document.getElementById('f_email').value = p ? (p.email||'') : '';
  document.getElementById('f_direccion').value = p ? (p.direccion||'') : '';
  document.getElementById('f_dias_credito').value = p ? (p.dias_credito||0) : 0;
  document.getElementById('f_dias_entrega').value = p ? (p.dias_entrega||0) : 0;
  document.getElementById('modalProveedor').classList.add('open');
}

function editarProveedor(id) {
  const p = proveedoresData.find(x => x.id == id);
  if (p) { abrirModal(p); return; }
  // Fallback: fetch by id if not in current data
  fetch(`api/proveedores/listar.php?search=&activo=0`)
    .then(r=>r.json())
    .then(d=>{
      if (d.success) {
        const p2 = d.data.find(x=>x.id==id);
        if (p2) abrirModal(p2);
      }
    });
}

function cerrarModal() {
  document.getElementById('modalProveedor').classList.remove('open');
}

async function guardarProveedor() {
  const id = document.getElementById('editId').value;
  const nombre = document.getElementById('f_nombre').value.trim();
  if (!nombre) return Swal.fire({icon:'warning',title:'Campo requerido',text:'El nombre del proveedor es obligatorio'});
  const body = {
    nombre, contacto_nombre: document.getElementById('f_contacto').value.trim() || null,
    telefono: document.getElementById('f_telefono').value.trim() || null,
    email: document.getElementById('f_email').value.trim() || null,
    direccion: document.getElementById('f_direccion').value.trim() || null,
    dias_credito: parseInt(document.getElementById('f_dias_credito').value) || 0,
    dias_entrega: parseInt(document.getElementById('f_dias_entrega').value) || 0
  };
  if (id) body.id = parseInt(id);
  try {
    const url = id ? 'api/proveedores/actualizar.php' : 'api/proveedores/crear.php';
    const res = await fetch(url, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
    const d = await res.json();
    if (d.success) {
      Swal.fire({icon:'success',title:'Guardado',text:d.message,toast:true,position:'top-end',showConfirmButton:false,timer:2000});
      cerrarModal();
      cargarProveedores();
    } else {
      Swal.fire({icon:'error',title:'Error',text:d.message});
    }
  } catch(e) {
    Swal.fire({icon:'error',title:'Error',text:'Fallo de red'});
  }
}

async function eliminarProveedor(id, nombre) {
  const r = await Swal.fire({
    title:'¿Desactivar proveedor?',
    text:`Se desactivará "${nombre}". Los datos históricos se conservan.`,
    icon:'warning',showCancelButton:true,confirmButtonColor:'#ef4444',
    confirmButtonText:'Sí, desactivar',cancelButtonText:'Cancelar'
  });
  if (!r.isConfirmed) return;
  try {
    const res = await fetch('api/proveedores/eliminar.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});
    const d = await res.json();
    if (d.success) {
      Swal.fire({icon:'success',title:'Desactivado',toast:true,position:'top-end',showConfirmButton:false,timer:2000});
      cargarProveedores();
    } else {
      Swal.fire({icon:'error',title:'Error',text:d.message});
    }
  } catch(e) { Swal.fire({icon:'error',title:'Error',text:'Fallo de red'}); }
}

function esc(t) { if(!t)return ''; const d=document.createElement('div');d.textContent=t;return d.innerHTML; }

cargarProveedores();
</script>
<?php renderFooter(); ?>

