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

if (!function_exists('esc')) {
    function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

$messages = [];

// ============================================
// ACTUALIZAR MÉTODO DE PAGO
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_payment') {
    $sale_id = isset($_POST['sale_id']) ? (int)$_POST['sale_id'] : 0;
    $payment_method = trim($_POST['payment_method'] ?? '');
    
    if ($sale_id <= 0) {
        $messages[] = ['type' => 'danger', 'text' => 'ID de venta inválido.'];
    } elseif (empty($payment_method)) {
        $messages[] = ['type' => 'danger', 'text' => 'Debe seleccionar un método de pago.'];
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE sales SET payment_method = ? WHERE id = ?");
            $stmt->execute([$payment_method, $sale_id]);
            $messages[] = ['type' => 'success', 'text' => 'Método de pago actualizado exitosamente.'];
        } catch (Exception $e) {
            $messages[] = ['type' => 'danger', 'text' => 'Error al actualizar: ' . $e->getMessage()];
        }
    }
}

// ============================================
// OBTENER TIPOS DE PAGO
// ============================================
$paymentTypes = [];
try {
    $stmt = $pdo->query("SELECT id, type FROM payment_types ORDER BY id ASC");
    $paymentTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $paymentTypes = [
        ['id' => 1, 'type' => 'cash'],
        ['id' => 2, 'type' => 'card'],
        ['id' => 3, 'type' => 'external'],
    ];
}

// ============================================
// OBTENER BOMBAS ACTIVAS
// ============================================
$pumps = $pdo->query("SELECT id, name, location FROM pumps ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);

?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Asignar Método de Pago</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <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>
    body {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .main-container {
      background: white;
      border-radius: 20px;
      margin: 30px auto;
      padding: 30px;
      max-width: 1400px;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
    
    .page-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 25px;
      border-radius: 15px;
      margin-bottom: 30px;
    }
    
    .page-header h3 {
      margin: 0;
      font-weight: 700;
    }
    
    .navbar {
      background: white !important;
      box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
    
    /* GRID DE BOMBAS */
    .pumps-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }
    
    .pump-card {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 15px;
      padding: 25px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      border: 3px solid transparent;
      box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    
    .pump-card:hover {
      transform: translateY(-8px);
      box-shadow: 0 10px 30px rgba(0,0,0,0.2);
      border-color: #667eea;
    }
    
    .pump-card.active {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-color: #764ba2;
      box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
    }
    
    .pump-icon {
      font-size: 48px;
      margin-bottom: 10px;
    }
    
    .pump-name {
      font-weight: 700;
      font-size: 18px;
      margin-bottom: 5px;
    }
    
    .pump-location {
      font-size: 13px;
      opacity: 0.8;
    }
    
    /* TABLA DE VENTAS */
    .sales-section {
      display: none;
      animation: fadeIn 0.5s ease;
    }
    
    .sales-section.active {
      display: block;
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    .sales-table-wrapper {
      background: white;
      border-radius: 15px;
      padding: 25px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    }
    
    .table {
      margin-bottom: 0;
    }
    
    .table thead th {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      padding: 15px 12px;
      font-weight: 600;
      text-transform: uppercase;
      font-size: 13px;
      letter-spacing: 0.5px;
    }
    
    .table tbody tr {
      transition: all 0.3s ease;
      cursor: pointer;
    }
    
    .table tbody tr:hover {
      background: #f8f9fa;
      transform: scale(1.01);
    }
    
    .table tbody td {
      padding: 15px 12px;
      vertical-align: middle;
      border-bottom: 1px solid #f1f1f1;
    }
    
    .badge-payment {
      padding: 8px 16px;
      border-radius: 8px;
      font-weight: 600;
      font-size: 13px;
    }
    
    .badge-cash { background: #10b981; color: white; }
    .badge-card { background: #3b82f6; color: white; }
    .badge-external { background: #f59e0b; color: white; }
    .badge-transfer { background: #8b5cf6; color: white; }
    .badge-default { background: #6b7280; color: white; }
    
    /* MODAL */
    .modal-content {
      border-radius: 20px;
      border: none;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
    
    .modal-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 20px 20px 0 0;
      padding: 20px 25px;
    }
    
    .modal-body {
      padding: 30px;
    }
    
    .payment-option {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border: 3px solid transparent;
      border-radius: 15px;
      padding: 20px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-bottom: 15px;
    }
    
    .payment-option:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 30px rgba(0,0,0,0.15);
      border-color: #667eea;
    }
    
    .payment-option input[type="radio"] {
      display: none;
    }
    
    .payment-option input[type="radio"]:checked + label {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    .payment-label {
      cursor: pointer;
      margin: 0;
      font-weight: 600;
      font-size: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }
    
    .btn {
      border-radius: 10px;
      padding: 12px 30px;
      font-weight: 600;
      transition: all 0.3s ease;
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
    
    .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }
    
    .no-sales {
      text-align: center;
      padding: 60px 20px;
      color: #6b7280;
    }
    
    .no-sales i {
      font-size: 64px;
      margin-bottom: 20px;
      opacity: 0.3;
    }
    
    .loading {
      text-align: center;
      padding: 40px;
      color: #667eea;
    }
    
    .loading i {
      font-size: 48px;
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  </style>
</head>
<body>

<nav class="navbar navbar-light">
  <div class="container-fluid">
    <a class="navbar-brand fw-bold" href="<?= site('index.php') ?>">
      <i class="bi bi-credit-card-2-front-fill"></i> Asignar Método de Pago
    </a>
    <div class="ms-auto d-flex gap-2">
      <a class="btn btn-outline-secondary btn-sm" href="<?= site('index.php') ?>">
        <i class="bi bi-arrow-left"></i> Volver
      </a>
      <a class="btn btn-outline-primary btn-sm" href="<?= site('admin/payment_types.php') ?>">
        <i class="bi bi-gear"></i> Gestionar Tipos
      </a>
    </div>
  </div>
</nav>

<div class="container-fluid">
  <div class="main-container">
    
    <div class="page-header">
      <h3><i class="bi bi-fuel-pump-fill"></i> Asignar Método de Pago por Bomba</h3>
      <p class="mb-0 mt-2" style="opacity:0.9">Selecciona una bomba para ver sus ventas y actualizar el método de pago</p>
    </div>

    <?php foreach ($messages as $m): ?>
      <div class="alert alert-<?= esc($m['type']) ?> alert-dismissible fade show" role="alert">
        <?= esc($m['text']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endforeach; ?>

    <!-- GRID DE BOMBAS -->
    <h5 class="mb-3"><i class="bi bi-list-ul"></i> Seleccionar Bomba</h5>
    <div class="pumps-grid">
      <?php if (empty($pumps)): ?>
        <div class="col-12">
          <div class="alert alert-info">
            <i class="bi bi-info-circle-fill"></i>
            No hay bombas registradas en el sistema.
          </div>
        </div>
      <?php else: ?>
        <?php foreach ($pumps as $pump): ?>
          <div class="pump-card" data-pump-id="<?= esc($pump['id']) ?>" onclick="selectPump(<?= esc($pump['id']) ?>, '<?= esc($pump['name']) ?>')">
            <div class="pump-icon"><i class="bi bi-fuel-pump"></i></div>
            <div class="pump-name"><?= esc($pump['name']) ?></div>
            <div class="pump-location"><?= esc($pump['location'] ?? 'Sin ubicación') ?></div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- SECCIÓN DE VENTAS -->
    <div class="sales-section" id="salesSection">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">
          <i class="bi bi-receipt"></i> 
          Ventas de <strong id="selectedPumpName">—</strong>
        </h5>
        <button class="btn btn-outline-secondary btn-sm" onclick="refreshSales()">
          <i class="bi bi-arrow-clockwise"></i> Actualizar
        </button>
      </div>
      
      <div class="sales-table-wrapper">
        <div id="salesTableContainer">
          <div class="loading">
            <i class="bi bi-hourglass-split"></i>
            <p>Cargando ventas...</p>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- MODAL PARA ASIGNAR MÉTODO DE PAGO -->
<div class="modal fade" id="paymentModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="bi bi-credit-card-fill"></i> Asignar Método de Pago
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="post" id="paymentForm">
        <input type="hidden" name="action" value="update_payment">
        <input type="hidden" name="sale_id" id="modalSaleId">
        
        <div class="modal-body">
          <div class="mb-3">
            <strong>Venta:</strong> <span id="modalSaleCode">—</span><br>
            <strong>Total:</strong> <span id="modalSaleTotal">—</span><br>
            <strong>Método actual:</strong> <span id="modalCurrentMethod">—</span>
          </div>
          
          <hr>
          
          <h6 class="mb-3"><i class="bi bi-list-check"></i> Seleccionar nuevo método:</h6>
          
          <div id="paymentOptions">
            <?php foreach ($paymentTypes as $pt): ?>
              <div class="payment-option">
                <input type="radio" name="payment_method" id="payment_<?= esc($pt['id']) ?>" value="<?= esc($pt['type']) ?>" required>
                <label for="payment_<?= esc($pt['id']) ?>" class="payment-label">
                  <i class="bi bi-<?= getPaymentIcon($pt['type']) ?>"></i>
                  <?= esc(ucfirst($pt['type'])) ?>
                </label>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
        
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
            <i class="bi bi-x-circle"></i> Cancelar
          </button>
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-check-circle"></i> Guardar
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let currentPumpId = null;
let paymentModal = null;

document.addEventListener('DOMContentLoaded', function() {
  paymentModal = new bootstrap.Modal(document.getElementById('paymentModal'));
});

function selectPump(pumpId, pumpName) {
  // Actualizar UI
  document.querySelectorAll('.pump-card').forEach(card => {
    card.classList.remove('active');
  });
  document.querySelector(`.pump-card[data-pump-id="${pumpId}"]`).classList.add('active');
  
  // Mostrar sección de ventas
  currentPumpId = pumpId;
  document.getElementById('selectedPumpName').textContent = pumpName;
  document.getElementById('salesSection').classList.add('active');
  
  // Cargar ventas
  loadSales(pumpId);
}

function loadSales(pumpId) {
  const container = document.getElementById('salesTableContainer');
  container.innerHTML = '<div class="loading"><i class="bi bi-hourglass-split"></i><p>Cargando ventas...</p></div>';
  
  fetch(`<?= site('api.php') ?>?action=get_pump_sales_detailed&pump_id=${pumpId}&limit=100`)
    .then(res => res.json())
    .then(data => {
      if (data.ok && Array.isArray(data.sales)) {
        renderSales(data.sales);
      } else {
        container.innerHTML = '<div class="no-sales"><i class="bi bi-inbox"></i><p>No se encontraron ventas para esta bomba.</p></div>';
      }
    })
    .catch(error => {
      container.innerHTML = '<div class="alert alert-danger"><i class="bi bi-exclamation-triangle-fill"></i> Error al cargar ventas.</div>';
      console.error('Error:', error);
    });
}

function renderSales(sales) {
  const container = document.getElementById('salesTableContainer');
  
  if (!sales || sales.length === 0) {
    container.innerHTML = '<div class="no-sales"><i class="bi bi-inbox"></i><p>No hay ventas registradas para esta bomba.</p></div>';
    return;
  }
  
  let html = '<table class="table table-hover">';
  html += '<thead><tr>';
  html += '<th><i class="bi bi-hash"></i> Código</th>';
  html += '<th><i class="bi bi-calendar3"></i> Fecha</th>';
  html += '<th><i class="bi bi-cash-stack"></i> Total</th>';
  html += '<th><i class="bi bi-credit-card"></i> Método de Pago</th>';
  html += '<th class="text-center"><i class="bi bi-gear"></i> Acción</th>';
  html += '</tr></thead><tbody>';
  
  sales.forEach(sale => {
    const total = sale.items.reduce((sum, item) => sum + parseFloat(item.total || 0), 0);
    const dateTime = new Date(sale.created_at).toLocaleString('es-DO', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
    
    // Obtener método de pago actual (necesitamos hacer otra consulta o agregarlo al API)
    html += '<tr onclick="openPaymentModal(' + sale.sale_id + ', \'' + escapeHtml(sale.sale_code) + '\', ' + total.toFixed(2) + ')">';
    html += '<td><strong>' + escapeHtml(sale.sale_code) + '</strong></td>';
    html += '<td><small>' + dateTime + '</small></td>';
    html += '<td><strong>$' + total.toFixed(2) + '</strong></td>';
    html += '<td><span class="badge badge-payment badge-default" id="badge_' + sale.sale_id + '">Cargando...</span></td>';
    html += '<td class="text-center"><button class="btn btn-sm btn-primary" onclick="event.stopPropagation(); openPaymentModal(' + sale.sale_id + ', \'' + escapeHtml(sale.sale_code) + '\', ' + total.toFixed(2) + ')"><i class="bi bi-pencil-fill"></i></button></td>';
    html += '</tr>';
  });
  
  html += '</tbody></table>';
  container.innerHTML = html;
  
  // Cargar métodos de pago actuales
  sales.forEach(sale => {
    fetch(`<?= site('api.php') ?>?action=get_recent_sales&limit=1000`)
      .then(res => res.json())
      .then(data => {
        if (data.ok && Array.isArray(data.sales)) {
          const saleData = data.sales.find(s => s.id == sale.sale_id);
          if (saleData) {
            updatePaymentBadge(sale.sale_id, saleData.payment_method || 'unknown');
          }
        }
      });
  });
}

function updatePaymentBadge(saleId, paymentMethod) {
  const badge = document.getElementById('badge_' + saleId);
  if (!badge) return;
  
  badge.textContent = paymentMethod.charAt(0).toUpperCase() + paymentMethod.slice(1);
  badge.className = 'badge badge-payment badge-' + paymentMethod.toLowerCase();
}

function openPaymentModal(saleId, saleCode, saleTotal) {
  document.getElementById('modalSaleId').value = saleId;
  document.getElementById('modalSaleCode').textContent = saleCode;
  document.getElementById('modalSaleTotal').textContent = '$' + saleTotal.toFixed(2);
  
  // Obtener método actual
  fetch(`<?= site('api.php') ?>?action=get_recent_sales&limit=1000`)
    .then(res => res.json())
    .then(data => {
      if (data.ok && Array.isArray(data.sales)) {
        const sale = data.sales.find(s => s.id == saleId);
        if (sale) {
          document.getElementById('modalCurrentMethod').textContent = sale.payment_method || 'No definido';
        }
      }
    });
  
  // Resetear selección
  document.querySelectorAll('input[name="payment_method"]').forEach(input => {
    input.checked = false;
  });
  
  paymentModal.show();
}

function refreshSales() {
  if (currentPumpId) {
    loadSales(currentPumpId);
  }
}

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// Auto-refresh cada 30 segundos
setInterval(() => {
  if (currentPumpId) {
    loadSales(currentPumpId);
  }
}, 30000);
</script>

</body>
</html>

<?php
function getPaymentIcon($type) {
  $icons = [
    'cash' => 'cash-stack',
    'card' => 'credit-card-fill',
    'external' => 'arrow-left-right',
    'transfer' => 'bank',
    'cheque' => 'receipt',
  ];
  return $icons[strtolower($type)] ?? 'wallet2';
}
?>