<?php
/**
 * API: Obtener registros filtrados de ventas (SufarmaERP)
 */

header('Content-Type: text/html; charset=utf-8');
require_once '../config/db_mysqli.php';

/** @var mysqli $conn */

$sucursal = $_POST['sucursal'] ?? '';
$fecha_inicio = $_POST['fecha_inicio'] ?? '';
$fecha_fin = $_POST['fecha_fin'] ?? '';
$filtro_estado = $_POST['estado_filtro'] ?? ''; // El nuevo filtro de 3 estados

$where = "WHERE 1=1";

if ($sucursal !== '') {
    $where .= " AND v.sucursal_id = '$sucursal'";
}

if ($fecha_inicio !== '' && $fecha_fin !== '') {
    $where .= " AND DATE(v.fecha_y_hora) BETWEEN '$fecha_inicio' AND '$fecha_fin'";
} elseif ($fecha_inicio !== '') {
    $where .= " AND DATE(v.fecha_y_hora) = '$fecha_inicio'";
}

// Lógica de filtrado base
if ($filtro_estado === 'POS_SIN_FACTURAR') {
    $where .= " AND dv.facturado = 0";
} elseif ($filtro_estado === 'POS_FACTURADO_PENDIENTE') {
    $where .= " AND dv.facturado = 1 AND dv.estado_factura != 'FACTURADO'";
} elseif ($filtro_estado === 'FEL_CERTIFICADO') {
    $where .= " AND dv.facturado = 1 AND dv.estado_factura = 'FACTURADO'";
}

// Consulta de ventas
$query = "SELECT v.id AS venta_id, v.fecha_y_hora, v.total, s.nombre AS sucursal,
                 dv.producto_id, dv.cantidad, dv.precio, dv.subtotal, p.NombreComercial, p.exento_iva,
                 dv.facturado, dv.estado_factura
          FROM ventas v 
          JOIN detalle_ventas dv ON v.id = dv.venta_id
          JOIN productos p ON dv.producto_id = p.id
          JOIN sucursales s ON v.sucursal_id = s.id
          $where        
          ORDER BY v.fecha_y_hora DESC";        

$result = $conn->query($query);

$sin_facturar = []; // POS Sin Facturar
$por_certificar = []; // POS Facturados, FEL Pendiente
$certificadas = []; // FEL Certificadas

/** @var mysqli $conn */
while ($row = mysqli_fetch_assoc($result)) {
    $venta_id = $row['venta_id'];
    
    // Categorización de 3 niveles
    if ($row['facturado'] == 0) {
        $target = 'sin_facturar';
    } elseif ($row['facturado'] == 1 && $row['estado_factura'] != 'FACTURADO') {
        $target = 'por_certificar';
    } else {
        $target = 'certificadas';
    }
    
    if (!isset(${$target}[$venta_id])) {
        ${$target}[$venta_id] = [
            'fecha' => $row['fecha_y_hora'],    
            'calculated_total' => 0, // Iniciar acumulador real
            'sucursal' => $row['sucursal'],     
            'detalles' => []
        ];
    }

    // Acumular solo lo que pasó por el filtro
    ${$target}[$venta_id]['calculated_total'] += (float)$row['subtotal'];
    
    ${$target}[$venta_id]['detalles'][] = [        
        'producto' => $row['NombreComercial'],  
        'cantidad' => $row['cantidad'],
        'precio' => $row['precio'],
        'subtotal' => $row['subtotal'],
        'exento_iva' => $row['exento_iva']
    ];
}

function renderVentas($lista, $tipo) {
    if (empty($lista)) {
        return "<div style='padding: 3rem 1rem; border-radius: 16px; border: 1px solid var(--border); background: rgba(255,255,255,0.01); text-align: center; color: var(--text-muted); margin-bottom: 1.5rem;'>
                    <i class='bi bi-inbox text-muted' style='font-size: 2.5rem; display: block; margin-bottom: 0.75rem; opacity: 0.35;'></i>
                    <span style='font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em;'>No se encontraron registros</span>
                </div>";
    }
    
    $html = "";
    foreach ($lista as $id => $venta) {
        $btn = "";
        $check = "";
        
        if ($tipo == 'por_certificar') {
            // Checkbox modernizado al lado del precio
            $check = "<input type='checkbox' class='venta-check' 
                        style='width:22px; height:22px; cursor:pointer; accent-color: var(--accent-color); margin: 0;' 
                        value='$id' data-monto='{$venta['calculated_total']}'>";
            $btn = "<button onclick='fel.openModal(\"$id\")' class='btn btn-primary' style='font-size:0.8rem; padding: 0.4rem 0.85rem; height: 32px;'>
                        <i class='bi bi-lightning-fill' style='margin-right: 0.25rem;'></i>Facturar C.F.
                    </button>";
        } elseif ($tipo == 'certificadas') {
            $btn = "<div class='badge-premium badge-soft-success'><i class='bi bi-check-all' style='margin-right: 0.25rem;'></i> CERTIFICADO</div>";
        } else {
            $btn = "<div class='badge-premium badge-soft-muted'><i class='bi bi-eye' style='margin-right: 0.25rem;'></i> CONSULTA</div>";
        }

        $html .= "<div class='card' style='margin-bottom: 1rem; padding: 0; overflow: hidden; border: 1px solid var(--border-color);'>
                <div style='display: flex; justify-content: space-between; align-items: center; padding: 1rem 1.5rem; border-bottom: 1px solid var(--border); flex-wrap: wrap; gap: 0.75rem;'>       
                    <div style='display: flex; align-items: center; gap: 0.75rem;'>
                        <div>
                            <div style='font-weight: bold; color: var(--text-primary); font-size: 0.9rem;'>Venta #$id</div>
                            <div style='font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.15rem;'>{$venta['fecha']} • <span style='font-weight: 600; color: var(--success);'>{$venta['sucursal']}</span></div>
                        </div>
                    </div>
                    <div style='display: flex; align-items: center; gap: 1rem;'>
                        <div style='display: flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0.85rem; border-radius: 8px; background: var(--surface-elevated); border: 1px solid var(--border);'>
                            $check
                            <div style='font-weight: 800; color: var(--success); font-size: 1.1rem; font-family: \"League Spartan\";'>Q" . number_format($venta['calculated_total'], 2) . "</div>
                        </div>
                        $btn
                    </div>
                </div>  
                <div style='overflow-x: auto;'>
                    <table class='table-premium' style='width: 100%; border-collapse: collapse;'>
                        <thead>
                            <tr style='border-bottom: 1px solid var(--border);'>
                                <th style='padding: 0.5rem 1rem; font-size: 0.75rem; color: var(--text-secondary); font-weight: 600;'>Producto / Servicio</th>
                                <th style='text-align: center; padding: 0.5rem 1rem; font-size: 0.75rem; color: var(--text-secondary); font-weight: 600; width: 80px;'>Cant.</th>
                                <th style='text-align: right; padding: 0.5rem 1rem; font-size: 0.75rem; color: var(--text-secondary); font-weight: 600; width: 100px;'>Precio</th>
                                <th style='text-align: right; padding: 0.5rem 1rem; font-size: 0.75rem; color: var(--text-secondary); font-weight: 600; width: 100px;'>Subtotal</th>
                                <th style='text-align: center; padding: 0.5rem 1rem; font-size: 0.75rem; color: var(--text-secondary); font-weight: 600; width: 100px;'>Exento</th>
                            </tr>
                        </thead>
                        <tbody>";
        foreach ($venta['detalles'] as $detalle) {
            $exento_label = ($detalle['exento_iva'] == 1) ? '<span class="badge-premium badge-soft-primary" style="font-size:0.6rem; padding: 2px 6px; border-radius: 4px;">EXENTO</span>' : '<span style="color: var(--text-muted); font-size: 0.75rem; opacity: 0.5;">-</span>';
            $html .= "<tr style='border-bottom: 1px solid var(--border-light);'>  
                    <td style='padding: 0.75rem 1rem; font-weight: 600; color: var(--text-primary);'>{$detalle['producto']}</td>
                    <td style='text-align: center; padding: 0.75rem 1rem; font-weight: bold; color: var(--text-secondary);'>{$detalle['cantidad']}</td>
                    <td style='text-align: right; padding: 0.75rem 1rem; color: var(--text-secondary); font-size: 0.8rem;'>Q" . number_format($detalle['precio'], 2) . "</td>
                    <td style='text-align: right; padding: 0.75rem 1rem; font-weight: bold; color: var(--text-primary);'>Q" . number_format($detalle['subtotal'], 2) . "</td>
                    <td style='text-align: center; padding: 0.75rem 1rem;'>$exento_label</td>
                  </tr>";
        }
        $html .= "      </tbody>
                    </table>
                </div>  
              </div>";
    }
    return $html;
}

// Cálculo de totales agregados
$sum_por_certificar = array_sum(array_column($por_certificar, 'calculated_total'));
$sum_certificadas = array_sum(array_column($certificadas, 'calculated_total'));
$sum_sin_facturar = array_sum(array_column($sin_facturar, 'calculated_total'));

// Renderizado por bloques
echo "<div style='margin-bottom: 2rem;'>";
echo "<div style='display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.25rem; flex-wrap: wrap; gap: 0.75rem;'>
        <div style='display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap;'>
            <div style='width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: #3b82f6; color: white; font-weight: bold;'>1</div>
            <h5 style='font-size: 1.15rem; font-weight: 800; font-family: \"League Spartan\"; color: white; margin: 0;'>Ventas por Certificar</h5>
            <div style='display: flex; gap: 0.5rem; margin-left: 0.5rem; flex-wrap: wrap;'>
                <div class='badge-premium' style='padding: 0.35rem 0.75rem; background: rgba(59, 130, 246, 0.08); border: 1px solid rgba(59, 130, 246, 0.2); border-radius: 8px; display: flex; flex-direction: column; align-items: center; justify-content: center; min-width: 110px;'>
                    <span style='font-size:0.6rem; opacity:0.8; color: #93c5fd; text-transform: uppercase; font-weight: 700; margin-bottom: 2px;'>Por Certificar</span>
                    <span style='color: #60a5fa; font-weight: 800; font-size: 0.95rem;' id='total_por_certificar'>Q" . number_format($sum_por_certificar, 2) . "</span>
                </div>
                <div class='badge-premium' style='padding: 0.35rem 0.75rem; background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.2); border-radius: 8px; display: flex; flex-direction: column; align-items: center; justify-content: center; min-width: 110px;'>
                    <span style='font-size:0.6rem; opacity:0.8; color: #6ee7b7; text-transform: uppercase; font-weight: 700; margin-bottom: 2px;'>Certificados</span>
                    <span style='color: #10b981; font-weight: 800; font-size: 0.95rem;' id='total_certificados'>Q" . number_format($sum_certificadas, 2) . "</span>
                </div>
                <div class='badge-premium' style='padding: 0.35rem 0.75rem; background: rgba(148, 163, 184, 0.08); border: 1px solid rgba(148, 163, 184, 0.2); border-radius: 8px; display: flex; flex-direction: column; align-items: center; justify-content: center; min-width: 110px;'>
                    <span style='font-size:0.6rem; opacity:0.8; color: #cbd5e1; text-transform: uppercase; font-weight: 700; margin-bottom: 2px;'>No Facturables</span>
                    <span style='color: #cbd5e1; font-weight: 800; font-size: 0.95rem;' id='total_no_facturables'>Q" . number_format($sum_sin_facturar, 2) . "</span>
                </div>
            </div>
        </div>
        <div style='display: flex; align-items: center; gap: 0.5rem;'>
            <button class='btn-export-excel-green' onclick='exportarExcel()'>
                <i class='bi bi-file-earmark-spreadsheet' style='margin-right: 0.25rem;'></i>Exportar Excel
            </button>
            <div style='position: relative; display: inline-block;'>
                <button class='btn btn-primary' onclick='fel.openUnifiedModal()' style='height: 38px;'>
                    <i class='bi bi-lightning-auto' style='margin-right: 0.25rem;'></i>Certificación Masiva
                </button>
                <div id='seleccion-total-container' style='display:none; position: absolute; left: 50%; transform: translateX(-50%); top: 100%; margin-top: 0.25rem; z-index: 100; width: max-content;'>
                    <span class='badge-premium' style='background: var(--surface-elevated); color: white; border: 1px solid var(--border); font-size: 0.7rem; padding: 4px 8px; border-radius: 6px; box-shadow: var(--shadow);'>
                        Selección: <span id='seleccion-total-badge' style='color: var(--success); font-weight: bold;'>Q0.00</span>
                    </span>
                </div>
            </div>
        </div>
      </div>";
echo renderVentas($por_certificar, 'por_certificar');
echo "</div>";

echo "<div style='margin-bottom: 2rem;'>";
echo "<div style='display: flex; align-items: center; margin-bottom: 1.25rem; gap: 0.75rem;'>
        <div style='width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: #10b981; color: white; font-weight: bold;'>2</div>
        <h5 style='font-size: 1.15rem; font-weight: 800; font-family: \"League Spartan\"; color: white; margin: 0;'>Documentos Certificados (FEL)</h5>
        <span class='badge-premium badge-soft-success' style='border-radius: 20px; padding: 3px 8px; font-size: 0.65rem;'>" . count($certificadas) . " registros</span>
      </div>";
echo renderVentas($certificadas, 'certificadas');
echo "</div>";

echo "<div style='margin-bottom: 2rem;'>";
echo "<div style='display: flex; align-items: center; margin-bottom: 1.25rem; gap: 0.75rem;'>
        <div style='width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: #64748b; color: white; font-weight: bold;'>3</div>
        <h5 style='font-size: 1.15rem; font-weight: 800; font-family: \"League Spartan\"; color: white; margin: 0;'>Ventas no Facturadas</h5>
        <span class='badge-premium badge-soft-muted' style='border-radius: 20px; padding: 3px 8px; font-size: 0.65rem;'>" . count($sin_facturar) . " registros</span>
      </div>";
echo renderVentas($sin_facturar, 'sin_facturar');
echo "</div>";

// Cálculo de totales agregados para el dashboard
$sum_por_certificar = array_sum(array_column($por_certificar, 'calculated_total'));
$sum_certificadas = array_sum(array_column($certificadas, 'calculated_total'));
$sum_sin_facturar = array_sum(array_column($sin_facturar, 'calculated_total'));

// Elemento transportador de datos (oculto)
echo "<div id='data-meta' style='display:none;' 
        data-por-certificar='".number_format($sum_por_certificar, 2, '.', '')."'
        data-certificados='".number_format($sum_certificadas, 2, '.', '')."'
        data-no-facturables='".number_format($sum_sin_facturar, 2, '.', '')."'></div>";
?>
