<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// INFORMACIÓN VALIOSA DEL USUARIO: CONFIGURACIÓN DE CONEXIÓN
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'veliziasystem_uinternacional');
define('DB_PASSWORD', 'Osito.1852570');
define('DB_NAME', 'veliziasystem_internacional');




class Db {
    protected $dbh;
    public function __construct(){ 
        try {
            date_default_timezone_set("America/Caracas");
            $this->dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USERNAME, DB_PASSWORD,
                [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"] );
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) { die("Error de conexión: " . $e->getMessage()); }
    }
    public function DBConsulta($sql) {
        $stmt = $this->dbh->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// PROCESAMIENTO DE FECHAS Y NUEVOS FILTROS
$fecha_inicio = $_GET['desde'] ?? date('Y-m-d');
$fecha_fin    = $_GET['hasta'] ?? date('Y-m-d');
$filtro_mesero = $_GET['mesero'] ?? ''; 
$filtro_ticket = $_GET['ticket'] ?? ''; 
$filtro_pago   = $_GET['pago'] ?? '';   

$tra = new Db();

// OBTENER TASA DE CAMBIO
$res_tasa = $tra->DBConsulta("SELECT montocambio FROM tiposcambio ORDER BY codcambio DESC LIMIT 1");
$tasa_dia = $res_tasa[0]['montocambio'] ?? 1;

// --- OBTENER TODOS LOS TIPOS DE PAGO EXISTENTES (Para el selector de filtro) ---
// Se obtiene la lista de pagos de forma robusta de formapago y formapago2
$pagos_sql = "SELECT DISTINCT formapago FROM ventas WHERE formapago IS NOT NULL AND formapago != ''
              UNION 
              SELECT DISTINCT formapago2 AS formapago FROM ventas WHERE formapago2 IS NOT NULL AND formapago2 != ''";
$tipos_pago = $tra->DBConsulta($pagos_sql);

// --- PREPARACIÓN DE LA CONSULTA SQL CON FILTROS ---
$where_clauses = ["DATE(V.fechaventa) BETWEEN '$fecha_inicio' AND '$fecha_fin'"];

// 1. FILTRO POR MESERO (Busca coincidencias parciales)
if (!empty($filtro_mesero)) {
    $where_clauses[] = "U.nombres LIKE '%" . $filtro_mesero . "%'";
}

// 2. FILTRO POR TICKET (Busca coincidencias parciales en codfactura o codventa)
if (!empty($filtro_ticket)) {
    $where_clauses[] = "(V.codfactura LIKE '%" . $filtro_ticket . "%' OR V.codventa LIKE '%" . $filtro_ticket . "%')";
}

// 3. FILTRO POR FORMA DE PAGO (Incluye Pagos Mixtos)
if (!empty($filtro_pago)) {
    // Caso especial: Pago Mixto
    if ($filtro_pago === 'Mixto') {
        // Un pago es mixto si se usó formapago2 con un monto positivo
        $where_clauses[] = "V.formapago2 IS NOT NULL AND V.formapago2 != '' AND V.montopagado2 > 0";
    } else {
        // Busca si el tipo de pago está en el pago 1 O en el pago 2
        $where_clauses[] = "(V.formapago = '" . $filtro_pago . "' OR V.formapago2 = '" . $filtro_pago . "')";
    }
}

// Combina todas las condiciones WHERE
$where_string = "WHERE " . implode(" AND ", $where_clauses);

// CONSULTA FINAL DE VENTAS
$sql = "SELECT V.*, S.nomsala, U.nombres as mesero_nombre
        FROM ventas V 
        LEFT JOIN mesas M ON V.codmesa = M.codmesa 
        LEFT JOIN salas S ON M.codsala = S.codsala 
        LEFT JOIN usuarios U ON V.codigo = U.codigo 
        $where_string
        ORDER BY V.fechaventa DESC";

$ventas = $tra->DBConsulta($sql);
$totales_globales = ['subtotal' => 0, 'iva' => 0, 'propina' => 0, 'total' => 0];
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Changsha aeropuerto internacional - Control de Ventas Interno</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-size: 11px; background: #f4f6f9; color: #333; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .main-card { background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); padding: 25px; }
        .table-header { background: #1a1a1a; color: #fff; text-transform: uppercase; letter-spacing: 1px; }
        .monto-usd { color: #0d6efd; font-weight: 700; display: block; font-size: 1.1em; }
        .monto-bs { color: #dc3545; font-size: 0.9em; display: block; font-style: italic; }
        .total-row { background-color: #fff9db !important; }
        .footer-final { background: #1a1a1a; color: #fff; font-size: 1.2em; }
        .filter-box { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; margin-bottom: 20px; }
        .badge-mesero { background: #e7f1ff; color: #0056b3; padding: 4px 8px; border-radius: 4px; font-weight: 600; }
        
        .badge-pago { font-size: 0.85em; margin-bottom: 2px; display: inline-block; width: 100%; }
        
        .btn-print-ticket { 
            float: right; 
            background: #ffc107; 
            color: #000; 
            border: none; 
            padding: 5px 10px; 
            border-radius: 5px;
            transition: 0.2s;
        }
        .btn-print-ticket:hover { background: #e0a800; transform: scale(1.1); }

        @media print { .filter-box, .btn-print, .btn-print-ticket { display: none; } }
    </style>
</head>
<body class="p-4">

<div class="container-fluid main-card">
    <div class="row align-items-center mb-4">
        <div class="col-md-6">
            <h3 class="m-0 fw-bold text-dark">Chan Sha 88</h3>
            <p class="text-muted mb-0">Control Interno de  Ventas, IVA (16%) y Propinas</p>
            <span class="badge bg-secondary">Periodo: <?=$fecha_inicio?> al <?=$fecha_fin?></span>
        </div>
        <div class="col-md-6 text-end">
            <div class="d-inline-block text-center p-2 border rounded bg-light">
                <small class="text-uppercase fw-bold d-block text-muted">Tasa de Cambio</small>
                <strong class="fs-5 text-danger">Bs. <?=number_format($tasa_dia, 2, ',', '.')?></strong>
            </div>
            <button onclick="window.print()" class="btn btn-dark btn-sm ms-2 btn-print">Imprimir Reporte Completo</button>
        </div>
    </div>

    <div class="filter-box">
        <form method="GET" class="row g-3 align-items-end mb-3">
            <div class="col-md-2">
                <label class="form-label fw-bold small">Desde:</label>
                <input type="date" name="desde" class="form-control form-control-sm" value="<?=$fecha_inicio?>">
            </div>
            <div class="col-md-2">
                <label class="form-label fw-bold small">Hasta:</label>
                <input type="date" name="hasta" class="form-control form-control-sm" value="<?=$fecha_fin?>">
            </div>
            
            <div class="col-md-2">
                <label class="form-label fw-bold small">Mesero:</label>
                <input type="text" name="mesero" class="form-control form-control-sm" value="<?=$filtro_mesero?>" placeholder="Nombre del mesero">
            </div>
            
            <div class="col-md-2">
                <label class="form-label fw-bold small">Ticket/Factura:</label>
                <input type="text" name="ticket" class="form-control form-control-sm" value="<?=$filtro_ticket?>" placeholder="ID Ticket/Factura">
            </div>

            <div class="col-md-2">
                <label class="form-label fw-bold small">Forma de Pago:</label>
                <select name="pago" class="form-select form-select-sm">
                    <option value="">— Todas —</option>
                    <option value="Mixto" <?php if($filtro_pago === 'Mixto') echo 'selected'; ?>>Pago Mixto</option>
                    <?php foreach(array_unique(array_column($tipos_pago, 'formapago')) as $pago): 
                        if (empty($pago)) continue; // Omitir si está vacío
                    ?>
                    <option value="<?=htmlentities($pago)?>" <?php if($filtro_pago === $pago) echo 'selected'; ?>>
                        <?= strtoupper(htmlentities($pago)) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary btn-sm w-100">Aplicar Filtros</button>
            </div>
        </form>
    </div>

    <table class="table table-bordered align-middle" id="tablaVentas">
        <thead class="table-header text-center small">
            <tr>
                <th width="18%">Identificación</th>
                <th width="18%">Detalle de Pago</th>
                <th>Subtotal (Neto)</th>
                <th>IVA (16%)</th>
                <th>Propina</th>
                <th>Total a Pagar</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($ventas as $v): 
                // Calculamos los totales EXACTAMENTE como lo hace el reporte
                $v_sub = (float)($v['subtotalivasi'] + $v['subtotalivano']);
                $v_iva = $v_sub * 0.16;
                $v_pro = (float)$v['montopropina'];
                $v_tot = $v_sub + $v_iva + $v_pro;

                $totales_globales['subtotal'] += $v_sub;
                $totales_globales['iva']      += $v_iva;
                $totales_globales['propina']  += $v_pro;
                $totales_globales['total']    += $v_tot;
            ?>
            <tr class="venta-row">
                <td class="searchable-ticket">
                    <a href="ticket_pdf.php?codventa=<?=$v['codventa']?>" target="_blank" class="btn-print-ticket" title="Imprimir Ticket">
                        <i class="fas fa-print"></i>
                    </a>
                    <div class="fw-bold text-dark">Ticket: <?=$v['codfactura']?></div>
                    <div class="small text-muted">ID Interno: <?=$v['codventa']?></div>
                    <div class="small text-muted">Pedido: <?=$v['codpedido']?></div>
                    <div class="mt-1"><span class="badge-mesero"><?=strtoupper($v['mesero_nombre'])?></span></div>
                </td>
                
                <td class="searchable-pago">
                    <?php if(!empty($v['formapago']) && $v['montopagado'] > 0): ?>
                    <div class="mb-2 border-bottom pb-1">
                        <span class="badge bg-primary badge-pago"><?= strtoupper($v['formapago']) ?></span>
                        <div class="fw-bold text-end">$<?=number_format($v['montopagado'], 2)?></div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if(!empty($v['formapago2']) && $v['montopagado2'] > 0): ?>
                    <div>
                        <span class="badge bg-info text-dark badge-pago"><?= strtoupper($v['formapago2']) ?> (Mixto)</span>
                        <div class="fw-bold text-end">$<?=number_format($v['montopagado2'], 2)?></div>
                    </div>
                    <?php endif; ?>
                </td>

                <td class="text-end">
                    <span class="monto-usd">$ <?=number_format($v_sub, 2)?></span>
                    <span class="monto-bs">Bs. <?=number_format($v_sub * $tasa_dia, 2, ',', '.')?></span>
                </td>
                <td class="text-end">
                    <span class="monto-usd">$ <?=number_format($v_iva, 2)?></span>
                    <span class="monto-bs">Bs. <?=number_format($v_iva * $tasa_dia, 2, ',', '.')?></span>
                </td>
                <td class="text-end">
                    <span class="monto-usd">$ <?=number_format($v_pro, 2)?></span>
                    <span class="monto-bs">Bs. <?=number_format($v_pro * $tasa_dia, 2, ',', '.')?></span>
                </td>
                <td class="text-end total-row">
                    <span class="monto-usd">$ <?=number_format($v_tot, 2)?></span>
                    <span class="monto-bs fw-bold">Bs. <?=number_format($v_tot * $tasa_dia, 2, ',', '.')?></span>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot class="footer-final text-end">
            <tr>
                <td colspan="2" class="text-center fw-bold">TOTALES GENERALES</td>
                <td>$ <?=number_format($totales_globales['subtotal'], 2)?><br><small>Bs. <?=number_format($totales_globales['subtotal'] * $tasa_dia, 2, ',', '.')?></small></td>
                <td>$ <?=number_format($totales_globales['iva'], 2)?><br><small>Bs. <?=number_format($totales_globales['iva'] * $tasa_dia, 2, ',', '.')?></small></td>
                <td>$ <?=number_format($totales_globales['propina'], 2)?><br><small>Bs. <?=number_format($totales_globales['propina'] * $tasa_dia, 2, ',', '.')?></small></td>
                <td class="bg-warning text-dark fw-bold">$ <?=number_format($totales_globales['total'], 2)?><br><span>Bs. <?=number_format($totales_globales['total'] * $tasa_dia, 2, ',', '.')?></span></td>
            </tr>
        </tfoot>
    </table>
</div>

</body>
</html>