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

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

// Filtros
$from_date = $_GET['from_date'] ?? date('Y-m-d', strtotime('-30 days'));
$to_date = $_GET['to_date'] ?? date('Y-m-d');
$empresa_filter = $_GET['empresa'] ?? '';
$empleado_filter = $_GET['empleado'] ?? '';
$export = $_GET['export'] ?? '';

// Construir query
$conditions = ["DATE(tc.created_at) BETWEEN ? AND ?"];
$params = [$from_date, $to_date];

if ($empresa_filter) {
    $conditions[] = "tc.codigo_empresa = ?";
    $params[] = $empresa_filter;
}

if ($empleado_filter) {
    $conditions[] = "tc.codigo_empleado = ?";
    $params[] = $empleado_filter;
}

$whereClause = implode(' AND ', $conditions);

// Obtener transacciones
$sql = "
    SELECT 
        tc.*,
        e.limite_credito,
        emp.nombre as empresa_nombre_full,
        emp.centro_costo
    FROM trans_creditos tc
    LEFT JOIN empleados e ON e.codigo_empleado = tc.codigo_empleado
    LEFT JOIN empresa emp ON emp.codigo = tc.codigo_empresa
    WHERE $whereClause
    ORDER BY tc.created_at DESC
    LIMIT 2000
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calcular totales
$total_debito = 0;
$total_credito = 0;
foreach ($transactions as $t) {
    $total_debito += (float)$t['debito'];
    $total_credito += (float)$t['credito'];
}

// Obtener listas para filtros
$empresas = $pdo->query("SELECT codigo, nombre FROM empresa ORDER BY nombre")->fetchAll(PDO::FETCH_ASSOC);
$empleados = $pdo->query("SELECT codigo_empleado, nombre, codigo_empresa FROM empleados ORDER BY nombre")->fetchAll(PDO::FETCH_ASSOC);

// Exportar CSV
if ($export === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="reporte_creditos_empleados_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    
    // BOM para UTF-8
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    
    fputcsv($out, [
        'ID', 'Fecha', 'Empresa', 'Empleado', 'Tarjeta', 
        'Venta', 'Débito', 'Crédito', 'Balance', 'Tipo', 'Descripción'
    ]);
    
    foreach ($transactions as $t) {
        fputcsv($out, [
            $t['id'],
            $t['created_at'],
            $t['nombre_empresa'],
            $t['nombre_empleado'],
            $t['codigo_tarjeta'],
            $t['sale_code'] ?? '',
            number_format($t['debito'], 2, '.', ''),
            number_format($t['credito'], 2, '.', ''),
            number_format($t['balance'], 2, '.', ''),
            $t['tipo_transaccion'],
            $t['descripcion']
        ]);
    }
    
    fclose($out);
    exit;
}

// Exportar PDF (básico con HTML)
if ($export === 'pdf') {
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Reporte Créditos Empleados</title>
        <style>
            body { font-family: Arial, sans-serif; font-size: 10px; }
            table { width: 100%; border-collapse: collapse; margin-top: 20px; }
            th, td { border: 1px solid #ddd; padding: 6px; text-align: left; }
            th { background: #667eea; color: white; }
            .text-end { text-align: right; }
            .header { text-align: center; margin-bottom: 20px; }
            .totals { margin-top: 20px; font-weight: bold; }
        </style>
    </head>
    <body onload="window.print()">
        <div class="header">
            <h2>Reporte de Créditos de Empleados</h2>
            <p>Período: <?= esc($from_date) ?> al <?= esc($to_date) ?></p>
            <p>Generado: <?= date('d/m/Y H:i:s') ?></p>
        </div>
        
        <table>
            <thead>
                <tr>
                    <th>Fecha</th>
                    <th>Empresa</th>
                    <th>Empleado</th>
                    <th>Venta</th>
                    <th class="text-end">Débito</th>
                    <th class="text-end">Crédito</th>
                    <th class="text-end">Balance</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($transactions as $t): ?>
                <tr>
                    <td><?= date('d/m/Y H:i', strtotime($t['created_at'])) ?></td>
                    <td><?= esc($t['nombre_empresa']) ?></td>
                    <td><?= esc($t['nombre_empleado']) ?></td>
                    <td><?= esc($t['sale_code'] ?? '-') ?></td>
                    <td class="text-end">$<?= number_format($t['debito'], 2) ?></td>
                    <td class="text-end">$<?= number_format($t['credito'], 2) ?></td>
                    <td class="text-end">$<?= number_format($t['balance'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <div class="totals">
            <p>Total Débitos: $<?= number_format($total_debito, 2) ?></p>
            <p>Total Créditos: $<?= number_format($total_credito, 2) ?></p>
            <p>Transacciones: <?= count($transactions) ?></p>
        </div>
    </body>
    </html>
    <?php
    exit;
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reporte Créditos Empleados</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;
  padding: 20px 0;
}

.page-container {
  max-width: 1600px;
  margin: 0 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 h1 {
  font-size: 32px;
  font-weight: 800;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0;
}

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

.filter-card h5 {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  margin-bottom: 20px;
}

.stats-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 30px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 13px;
  opacity: 0.9;
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 32px;
  font-weight: 800;
  line-height: 1;
}

.table-card {
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.1);
  overflow: hidden;
}

.table-responsive {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table thead {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.data-table thead th {
  padding: 15px 12px;
  text-align: left;
  font-weight: 600;
  text-transform: uppercase;
  font-size: 12px;
  letter-spacing: 0.5px;
  white-space: nowrap;
}

.data-table tbody td {
  padding: 15px 12px;
  border-bottom: 1px solid #f0f0f0;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.badge-debito {
  background: linear-gradient(135deg, #ff6a00 0%, #ee0979 100%);
  color: white;
}

.badge-credito {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
}

.badge-ajuste {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-custom {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-primary-custom {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

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

.btn-success-custom {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
}

.btn-success-custom:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(17, 153, 142, 0.4);
}

.btn-danger-custom {
  background: linear-gradient(135deg, #ff6a00 0%, #ee0979 100%);
  color: white;
}

.btn-danger-custom:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(238, 9, 121, 0.4);
}

.btn-outline-custom {
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-outline-custom:hover {
  background: #667eea;
  color: white;
}

.text-end {
  text-align: right;
}

.text-debito {
  color: #ee0979;
  font-weight: 700;
}

.text-credito {
  color: #11998e;
  font-weight: 700;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-state i {
  font-size: 64px;
  opacity: 0.3;
  margin-bottom: 20px;
  display: block;
}

@media (max-width: 768px) {
  .stats-bar {
    flex-direction: column;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table thead th,
  .data-table tbody td {
    padding: 10px 8px;
  }
}

@media print {
  body {
    background: white;
  }
  
  .no-print {
    display: none !important;
  }
  
  .page-container {
    max-width: 100%;
  }
}
</style>
</head>
<body>

<div class="page-container">
  
  <!-- HEADER -->
  <div class="page-header">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
      <div>
        <h1><i class="bi bi-file-earmark-bar-graph"></i> Reporte de Créditos de Empleados</h1>
        <p class="text-muted mb-0">Consulta y exporta transacciones de crédito corporativo</p>
      </div>
      <a href="<?= site('admin/index.php') ?>" class="btn btn-outline-custom btn-custom no-print">
        <i class="bi bi-arrow-left"></i> Volver
      </a>
    </div>
  </div>
  
  <!-- FILTROS -->
  <div class="filter-card no-print">
    <h5><i class="bi bi-funnel-fill"></i> Filtros de Búsqueda</h5>
    
    <form method="get" class="row g-3">
      <div class="col-md-3">
        <label class="form-label fw-bold">Desde</label>
        <input type="date" name="from_date" class="form-control" value="<?= esc($from_date) ?>" required>
      </div>
      
      <div class="col-md-3">
        <label class="form-label fw-bold">Hasta</label>
        <input type="date" name="to_date" class="form-control" value="<?= esc($to_date) ?>" required>
      </div>
      
      <div class="col-md-3">
        <label class="form-label fw-bold">Empresa</label>
        <select name="empresa" class="form-select" id="empresaSelect">
          <option value="">Todas las empresas</option>
          <?php foreach ($empresas as $emp): ?>
            <option value="<?= esc($emp['codigo']) ?>" <?= $empresa_filter === $emp['codigo'] ? 'selected' : '' ?>>
              <?= esc($emp['nombre']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      
      <div class="col-md-3">
        <label class="form-label fw-bold">Empleado</label>
        <select name="empleado" class="form-select" id="empleadoSelect">
          <option value="">Todos los empleados</option>
          <?php foreach ($empleados as $empl): ?>
            <option value="<?= esc($empl['codigo_empleado']) ?>" 
                    data-empresa="<?= esc($empl['codigo_empresa']) ?>"
                    <?= $empleado_filter === $empl['codigo_empleado'] ? 'selected' : '' ?>>
              <?= esc($empl['nombre']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      
      <div class="col-12">
        <div class="d-flex gap-2 flex-wrap">
          <button type="submit" class="btn btn-primary-custom btn-custom">
            <i class="bi bi-search"></i> Buscar
          </button>
          <a href="<?= site('admin/reporte_credito_empleado.php') ?>" class="btn btn-outline-custom btn-custom">
            <i class="bi bi-arrow-clockwise"></i> Limpiar
          </a>
          <?php
            $exportParams = $_GET;
            $exportParams['export'] = 'csv';
            $csvUrl = site('admin/reporte_credito_empleado.php') . '?' . http_build_query($exportParams);
            
            $exportParams['export'] = 'pdf';
            $pdfUrl = site('admin/reporte_credito_empleado.php') . '?' . http_build_query($exportParams);
          ?>
          <a href="<?= $csvUrl ?>" class="btn btn-success-custom btn-custom">
            <i class="bi bi-filetype-csv"></i> Exportar CSV
          </a>
          <a href="<?= $pdfUrl ?>" target="_blank" class="btn btn-danger-custom btn-custom">
            <i class="bi bi-file-pdf"></i> Exportar PDF
          </a>
        </div>
      </div>
    </form>
  </div>
  
  <!-- STATS -->
  <?php if (count($transactions) > 0): ?>
  <div class="stats-bar">
    <div class="stat-item">
      <div class="stat-label">Total Transacciones</div>
      <div class="stat-value"><?= number_format(count($transactions)) ?></div>
    </div>
    <div class="stat-item">
      <div class="stat-label">Total Débitos</div>
      <div class="stat-value">$<?= number_format($total_debito, 2) ?></div>
    </div>
    <div class="stat-item">
      <div class="stat-label">Total Créditos</div>
      <div class="stat-value">$<?= number_format($total_credito, 2) ?></div>
    </div>
    <div class="stat-item">
      <div class="stat-label">Diferencia</div>
      <div class="stat-value">$<?= number_format($total_debito - $total_credito, 2) ?></div>
    </div>
  </div>
  <?php endif; ?>
  
  <!-- TABLA DE DATOS -->
  <div class="table-card">
    <div class="table-responsive">
      <?php if (count($transactions) === 0): ?>
        <div class="empty-state">
          <i class="bi bi-inbox"></i>
          <h4>No se encontraron transacciones</h4>
          <p>Intenta ajustar los filtros de búsqueda</p>
        </div>
      <?php else: ?>
        <table class="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Fecha</th>
              <th>Empresa</th>
              <th>Empleado</th>
              <th>Tarjeta</th>
              <th>Venta</th>
              <th class="text-end">Débito</th>
              <th class="text-end">Crédito</th>
              <th class="text-end">Balance</th>
              <th>Tipo</th>
              <th>Descripción</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($transactions as $t): ?>
            <tr>
              <td><strong>#<?= $t['id'] ?></strong></td>
              <td><?= date('d/m/Y H:i', strtotime($t['created_at'])) ?></td>
              <td>
                <strong><?= esc($t['nombre_empresa']) ?></strong><br>
                <small class="text-muted"><?= esc($t['codigo_empresa']) ?></small>
              </td>
              <td>
                <strong><?= esc($t['nombre_empleado']) ?></strong><br>
                <small class="text-muted"><?= esc($t['codigo_empleado']) ?></small>
              </td>
              <td>
                <code><?= esc($t['codigo_tarjeta'] ?? '-') ?></code>
              </td>
              <td>
                <?php if ($t['sale_code']): ?>
                  <strong><?= esc($t['sale_code']) ?></strong>
                <?php else: ?>
                  <span class="text-muted">-</span>
                <?php endif; ?>
              </td>
              <td class="text-end">
                <?php if ($t['debito'] > 0): ?>
                  <span class="text-debito">$<?= number_format($t['debito'], 2) ?></span>
                <?php else: ?>
                  <span class="text-muted">-</span>
                <?php endif; ?>
              </td>
              <td class="text-end">
                <?php if ($t['credito'] > 0): ?>
                  <span class="text-credito">$<?= number_format($t['credito'], 2) ?></span>
                <?php else: ?>
                  <span class="text-muted">-</span>
                <?php endif; ?>
              </td>
              <td class="text-end">
                <strong>$<?= number_format($t['balance'], 2) ?></strong>
              </td>
              <td>
                <?php
                  $badgeClass = 'badge-debito';
                  if ($t['tipo_transaccion'] === 'credito') $badgeClass = 'badge-credito';
                  if ($t['tipo_transaccion'] === 'ajuste') $badgeClass = 'badge-ajuste';
                ?>
                <span class="badge <?= $badgeClass ?>">
                  <?= esc($t['tipo_transaccion']) ?>
                </span>
              </td>
              <td>
                <small><?= esc($t['descripcion']) ?></small>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </div>
  
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Filtrar empleados por empresa
document.getElementById('empresaSelect').addEventListener('change', function() {
  const empresaCodigo = this.value;
  const empleadoSelect = document.getElementById('empleadoSelect');
  const options = empleadoSelect.querySelectorAll('option');
  
  options.forEach(opt => {
    if (opt.value === '') {
      opt.style.display = '';
      return;
    }
    
    const empEmpresa = opt.getAttribute('data-empresa');
    
    if (empresaCodigo === '' || empEmpresa === empresaCodigo) {
      opt.style.display = '';
    } else {
      opt.style.display = 'none';
    }
  });
  
  if (empleadoSelect.selectedOptions[0].style.display === 'none') {
    empleadoSelect.value = '';
  }
});

window.addEventListener('DOMContentLoaded', function() {
  const empresaSelect = document.getElementById('empresaSelect');
  if (empresaSelect.value) {
    empresaSelect.dispatchEvent(new Event('change'));
  }
});
</script>

</body>
</html>