<?php
require __DIR__ . '/init.php';
require_login();
$pdo = pdo();

$user_id = $_SESSION['user_id'] ?? 0;
$username = $_SESSION['username'] ?? 'Usuario';
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Créditos Empleados - FuelPOS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Inter', sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.top-navbar {
  background: white;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-brand {
  font-size: 24px;
  font-weight: 800;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.main-container {
  max-width: 1400px;
  margin: 30px auto;
  padding: 0 20px;
}

.page-header {
  background: white;
  border-radius: 20px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.1);
}

.page-header h2 {
  font-size: 28px;
  font-weight: 800;
  color: #333;
  margin: 0;
}

.pumps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.pump-card {
  background: white;
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.pump-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.pump-card:hover::before {
  transform: scaleX(1);
}

.pump-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(0,0,0,0.15);
}

.pump-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: white;
}

.pump-name {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  margin-bottom: 5px;
}

.pump-location {
  font-size: 13px;
  color: #666;
}

.modal-content {
  border-radius: 20px;
  border: none;
}

.modal-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px 20px 0 0;
  padding: 20px 30px;
  border: none;
}

.modal-body {
  padding: 30px;
}

.sale-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.sale-item:hover {
  background: #e9ecef;
  border-color: #667eea;
  transform: translateX(5px);
}

.sale-item.selected {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  border-color: #667eea;
}

.company-card {
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.company-card:hover {
  border-color: #667eea;
  background: #f8f9fa;
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.company-card.selected {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  border-color: #667eea;
  border-width: 3px;
}

.camera-container {
  position: relative;
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  border-radius: 15px;
  overflow: hidden;
  background: #000;
}

#camera-video {
  width: 100%;
  height: auto;
  display: block;
  transform: scaleX(-1); /* Espejo para facilitar lectura */
}

.camera-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  height: 60%;
  border: 3px solid #00ff00;
  border-radius: 10px;
  pointer-events: none;
  box-shadow: 0 0 0 9999px rgba(0,0,0,0.5);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  padding: 12px 30px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.loading-spinner {
  display: none;
  text-align: center;
  padding: 40px;
}

.loading-spinner.active {
  display: block;
}

.alert {
  border-radius: 12px;
  border: none;
  padding: 15px 20px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.pump-card {
  animation: fadeIn 0.5s ease;
}

.pump-card:nth-child(1) { animation-delay: 0.05s; }
.pump-card:nth-child(2) { animation-delay: 0.1s; }
.pump-card:nth-child(3) { animation-delay: 0.15s; }
.pump-card:nth-child(4) { animation-delay: 0.2s; }
.pump-card:nth-child(5) { animation-delay: 0.25s; }
.pump-card:nth-child(6) { animation-delay: 0.3s; }

.camera-status {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}
</style>
</head>
<body>

<nav class="top-navbar">
  <div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center">
      <div class="nav-brand">
        <i class="bi bi-credit-card-fill"></i>
        Créditos Empleados
      </div>
      <a href="<?= site('cashier_dashboard.php') ?>" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-left"></i> Volver
      </a>
    </div>
  </div>
</nav>

<div class="main-container">
  
  <div class="page-header">
    <h2><i class="bi bi-fuel-pump-fill"></i> Selecciona una Isla</h2>
    <p class="text-muted mb-0">Haz clic en una isla para ver sus ventas pendientes de asignación</p>
  </div>
  
  <div id="pumpsGrid" class="pumps-grid"></div>
  
</div>

<!-- MODAL: VENTAS DE LA BOMBA -->
<div class="modal fade" id="salesModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="bi bi-receipt-cutoff"></i>
          Ventas de <span id="modalPumpName"></span>
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="salesList"></div>
        <div class="loading-spinner" id="loadingSales">
          <div class="spinner-border text-primary" role="status"></div>
          <p class="mt-3">Cargando ventas...</p>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- MODAL: SELECCIONAR EMPRESA -->
<div class="modal fade" id="companyModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="bi bi-building"></i>
          Selecciona una Empresa
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <input type="text" class="form-control form-control-lg" id="searchCompany" placeholder="Buscar empresa...">
        </div>
        <div id="companyList"></div>
        <div class="loading-spinner" id="loadingCompanies">
          <div class="spinner-border text-primary" role="status"></div>
          <p class="mt-3">Cargando empresas...</p>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- MODAL: INGRESAR CÓDIGO DE TARJETA -->
<div class="modal fade" id="cardModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="bi bi-credit-card-2-back"></i>
          Código de Tarjeta
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-info">
          <i class="bi bi-info-circle"></i>
          Ingresa el código de la tarjeta del empleado o escanéalo con la cámara
        </div>
        
        <div class="mb-3">
          <label class="form-label fw-bold">Código de Tarjeta</label>
          <input type="text" class="form-control form-control-lg" id="cardCode" placeholder="Ej: CARD-0001" autofocus>
        </div>
        
        <div class="d-grid gap-2 mb-3">
          <button type="button" class="btn btn-primary btn-lg" onclick="processEmployeeCredit()">
            <i class="bi bi-check-circle"></i> Asignar Crédito
          </button>
          <button type="button" class="btn btn-outline-primary" onclick="startCamera()" id="btnCamera">
            <i class="bi bi-camera-fill"></i> Escanear con Cámara
          </button>
        </div>
        
        <!-- CÁMARA -->
        <div id="cameraSection" style="display:none;">
          <div class="camera-status" id="cameraStatus">
            <i class="bi bi-camera-video"></i> Iniciando cámara...
          </div>
          <div class="camera-container" id="cameraContainer" style="display:none;">
            <video id="camera-video" autoplay playsinline></video>
            <div class="camera-overlay"></div>
          </div>
          <canvas id="camera-canvas" style="display:none;"></canvas>
          <div class="d-grid gap-2 mt-3">
            <button type="button" class="btn btn-danger" onclick="stopCamera()">
              <i class="bi bi-x-circle"></i> Cerrar Cámara
            </button>
          </div>
        </div>
        
        <div id="cardResult"></div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/@zxing/library@latest"></script>

<script>
const API_URL = '<?= site('api.php') ?>';
let selectedSale = null;
let selectedCompany = null;
let cameraStream = null;
let codeReader = null;

// CARGAR BOMBAS
async function loadPumps() {
  try {
    const res = await fetch(`${API_URL}?action=get_pumps&t=${Date.now()}`);
    const data = await res.json();
    
    if (data.ok && Array.isArray(data.pumps)) {
      renderPumps(data.pumps);
    }
  } catch (e) {
    console.error('Error loading pumps:', e);
  }
}

function renderPumps(pumps) {
  const grid = document.getElementById('pumpsGrid');
  grid.innerHTML = '';
  
  pumps.forEach(pump => {
    grid.innerHTML += `
      <div class="pump-card" onclick="loadPumpSales(${pump.id}, '${pump.name}')">
        <div class="pump-icon">
          <i class="bi bi-fuel-pump-fill"></i>
        </div>
        <div class="pump-name">${pump.name}</div>
        <div class="pump-location">${pump.location || 'Isla'}</div>
      </div>
    `;
  });
}

// CARGAR VENTAS DE LA BOMBA
async function loadPumpSales(pumpId, pumpName) {
  document.getElementById('modalPumpName').textContent = pumpName;
  document.getElementById('loadingSales').classList.add('active');
  document.getElementById('salesList').innerHTML = '';
  
  const modal = new bootstrap.Modal(document.getElementById('salesModal'));
  modal.show();
  
  try {
    const res = await fetch(`${API_URL}?action=get_pump_sales_detailed&pump_id=${pumpId}&limit=50&t=${Date.now()}`);
    const data = await res.json();
    
    document.getElementById('loadingSales').classList.remove('active');
    
    if (data.ok && Array.isArray(data.sales)) {
      renderSales(data.sales);
    } else {
      document.getElementById('salesList').innerHTML = '<div class="alert alert-warning">No hay ventas disponibles</div>';
    }
  } catch (e) {
    console.error('Error loading sales:', e);
    document.getElementById('loadingSales').classList.remove('active');
    document.getElementById('salesList').innerHTML = '<div class="alert alert-danger">Error cargando ventas</div>';
  }
}

function renderSales(sales) {
  const list = document.getElementById('salesList');
  
  if (!sales.length) {
    list.innerHTML = '<div class="alert alert-info">No hay ventas pendientes</div>';
    return;
  }
  
  list.innerHTML = '';
  sales.forEach(sale => {
    const total = sale.items.reduce((sum, item) => sum + parseFloat(item.total || 0), 0);
    const date = new Date(sale.created_at);
    
    list.innerHTML += `
      <div class="sale-item" onclick="selectSale(${sale.sale_id}, '${sale.sale_code}', ${total})">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <strong>${sale.sale_code}</strong><br>
            <small class="text-muted">
              <i class="bi bi-clock"></i> ${date.toLocaleString('es-ES')}
            </small>
          </div>
          <div class="text-end">
            <div class="h5 mb-0 text-primary">$${total.toFixed(2)}</div>
            <small class="text-muted">${sale.items.length} items</small>
          </div>
        </div>
      </div>
    `;
  });
}

function selectSale(saleId, saleCode, total) {
  selectedSale = { id: saleId, code: saleCode, total: total };
  
  document.querySelectorAll('.sale-item').forEach(el => el.classList.remove('selected'));
  event.target.closest('.sale-item').classList.add('selected');
  
  bootstrap.Modal.getInstance(document.getElementById('salesModal')).hide();
  loadCompanies();
}

// CARGAR EMPRESAS
async function loadCompanies() {
  document.getElementById('loadingCompanies').classList.add('active');
  document.getElementById('companyList').innerHTML = '';
  
  const modal = new bootstrap.Modal(document.getElementById('companyModal'));
  modal.show();
  
  try {
    const res = await fetch(`${API_URL}?action=get_companies&t=${Date.now()}`);
    const data = await res.json();
    
    document.getElementById('loadingCompanies').classList.remove('active');
    
    if (data.ok && Array.isArray(data.companies)) {
      renderCompanies(data.companies);
    }
  } catch (e) {
    console.error('Error loading companies:', e);
    document.getElementById('loadingCompanies').classList.remove('active');
  }
}

function renderCompanies(companies) {
  const list = document.getElementById('companyList');
  
  if (!companies.length) {
    list.innerHTML = '<div class="alert alert-warning">No hay empresas registradas</div>';
    return;
  }
  
  list.innerHTML = '';
  companies.forEach(comp => {
    list.innerHTML += `
      <div class="company-card" onclick="selectCompany('${comp.codigo}', '${comp.nombre}')">
        <h6 class="mb-1"><strong>${comp.nombre}</strong></h6>
        <div class="text-muted small">
          <i class="bi bi-briefcase"></i> ${comp.codigo}
          ${comp.contacto ? `<span class="mx-2">|</span><i class="bi bi-person"></i> ${comp.contacto}` : ''}
        </div>
      </div>
    `;
  });
}

document.addEventListener('DOMContentLoaded', function() {
  const searchInput = document.getElementById('searchCompany');
  if (searchInput) {
    searchInput.addEventListener('input', function() {
      const query = this.value.toLowerCase();
      document.querySelectorAll('.company-card').forEach(card => {
        const text = card.textContent.toLowerCase();
        card.style.display = text.includes(query) ? '' : 'none';
      });
    });
  }
});

function selectCompany(codigo, nombre) {
  selectedCompany = { codigo: codigo, nombre: nombre };
  
  document.querySelectorAll('.company-card').forEach(el => el.classList.remove('selected'));
  event.target.closest('.company-card').classList.add('selected');
  
  bootstrap.Modal.getInstance(document.getElementById('companyModal')).hide();
  setTimeout(() => {
    const cardModal = new bootstrap.Modal(document.getElementById('cardModal'));
    cardModal.show();
    document.getElementById('cardCode').focus();
  }, 300);
}

// PROCESAR CRÉDITO
async function processEmployeeCredit() {
  const cardCode = document.getElementById('cardCode').value.trim();
  
  if (!cardCode) {
    alert('Por favor ingresa el código de la tarjeta');
    return;
  }
  
  if (!selectedSale || !selectedCompany) {
    alert('Error: Faltan datos de la venta o empresa');
    return;
  }
  
  try {
    const payload = {
      action: 'assign_employee_credit',
      sale_id: selectedSale.id,
      sale_code: selectedSale.code,
      total: selectedSale.total,
      codigo_empresa: selectedCompany.codigo,
      nombre_empresa: selectedCompany.nombre,
      codigo_tarjeta: cardCode,
      user_id: <?= $user_id ?>
    };
    
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    
    const data = await res.json();
    
    if (data.ok) {
      document.getElementById('cardResult').innerHTML = `
        <div class="alert alert-success">
          <i class="bi bi-check-circle"></i> ${data.message || 'Crédito asignado correctamente'}
        </div>
      `;
      
      setTimeout(() => {
        bootstrap.Modal.getInstance(document.getElementById('cardModal')).hide();
        location.reload();
      }, 1500);
    } else {
      document.getElementById('cardResult').innerHTML = `
        <div class="alert alert-danger">
          <i class="bi bi-exclamation-triangle"></i> ${data.message || 'Error al asignar crédito'}
        </div>
      `;
    }
  } catch (e) {
    console.error('Error:', e);
    document.getElementById('cardResult').innerHTML = `
      <div class="alert alert-danger">
        <i class="bi bi-exclamation-triangle"></i> Error de conexión
      </div>
    `;
  }
}

// ✅ CÁMARA CON ZXing (Compatible con Android Chrome)
async function startCamera() {
  const videoElement = document.getElementById('camera-video');
  const cameraSection = document.getElementById('cameraSection');
  const cameraContainer = document.getElementById('cameraContainer');
  const cameraStatus = document.getElementById('cameraStatus');
  const btnCamera = document.getElementById('btnCamera');
  
  cameraSection.style.display = 'block';
  cameraStatus.innerHTML = '<i class="bi bi-camera-video"></i> Iniciando cámara...';
  btnCamera.disabled = true;
  
  try {
    // Verificar si MediaDevices está disponible
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      throw new Error('Tu navegador no soporta acceso a la cámara. Usa Chrome o Firefox actualizado.');
    }
    
    // Solicitar cámara trasera (ideal para escanear)
    cameraStream = await navigator.mediaDevices.getUserMedia({ 
      video: { 
        facingMode: 'environment',
        width: { ideal: 1280 },
        height: { ideal: 720 }
      } 
    });
    
    videoElement.srcObject = cameraStream;
    cameraStatus.style.display = 'none';
    cameraContainer.style.display = 'block';
    
    // Iniciar ZXing BarcodeReader
    codeReader = new ZXing.BrowserBarcodeReader();
    
    codeReader.decodeFromVideoDevice(null, 'camera-video', (result, err) => {
      if (result) {
        document.getElementById('cardCode').value = result.text;
        stopCamera();
        document.getElementById('cardResult').innerHTML = `
          <div class="alert alert-success">
            <i class="bi bi-check-circle"></i> Código escaneado: <strong>${result.text}</strong>
          </div>
        `;
        // Auto-procesar
        setTimeout(() => processEmployeeCredit(), 500);
      }
      
      if (err && !(err instanceof ZXing.NotFoundException)) {
        console.error('Error escaneando:', err);
      }
    });
    
  } catch (e) {
    console.error('Error al acceder a la cámara:', e);
    cameraStatus.innerHTML = `
      <div class="alert alert-danger">
        <i class="bi bi-exclamation-triangle"></i> 
        <strong>Error:</strong> ${e.message}
        <hr>
        <small>Asegúrate de dar permisos de cámara en Chrome.</small>
      </div>
    `;
    btnCamera.disabled = false;
  }
}

function stopCamera() {
  if (codeReader) {
    codeReader.reset();
    codeReader = null;
  }
  
  if (cameraStream) {
    cameraStream.getTracks().forEach(track => track.stop());
    cameraStream = null;
  }
  
  document.getElementById('cameraSection').style.display = 'none';
  document.getElementById('cameraContainer').style.display = 'none';
  document.getElementById('cameraStatus').style.display = 'block';
  document.getElementById('btnCamera').disabled = false;
}

// ENTER KEY EN CAMPO DE TARJETA
document.addEventListener('DOMContentLoaded', function() {
  const cardInput = document.getElementById('cardCode');
  if (cardInput) {
    cardInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        processEmployeeCredit();
      }
    });
  }
});

// INICIALIZAR
loadPumps();
</script>

</body>
</html>