<?php
session_start();
require_once "../librerias/Conexion.php";

$folio = $_SESSION['ticket_folio'] ?? $_GET['folio'] ?? null;

$idUser   = $_SESSION['empresa_idu']?? 1; 

if (!$folio) { die("<script>window.location.href='PageNV.php';</script>"); }

$db = new Conexion("MS_Datos"); 

// 1. CONSULTA MAESTRA (Venta + Cliente)
$sql = "SELECT v.*, c.IDC, c.Nombre as ClienteNom, c.Email as ClienteEmail, 
               c.Telefono as ClienteTel, c.Datos_Fiscales as FiscalJSON
        FROM `$idUser-Ventas_Cabecera` v
        LEFT JOIN `$idUser-Clientes` c ON v.IDC_Cliente = c.IDC
        WHERE v.Folio = '$folio' LIMIT 1";
//echo $sql;
$res = $db->obtenerDatos($sql);
//print_r($res);
$venta = $res['data'][0] ?? null;

if (!$venta) { die("Error: Folio inexistente."); }

// 2. VERIFICAR SI YA EXISTE UNA SOLICITUD (Validación de duplicados)
$sqlCheck = "SELECT Estado FROM `$idUser-Facturacion_Solicitudes` WHERE ID_Venta = '{$venta['ID_Venta']}'";
$resCheck = $db->obtenerDatos($sqlCheck);
$yaSolicitado = !empty($resCheck['data']);

// 3. CÁLCULO DE IVA PARA VALIDACIÓN
$subtotalReal = (float)$venta['Subtotal'] - (float)$venta['Descuento'];
$ivaPagado = (float)$venta['Total'] - $subtotalReal;
$tieneIVA = ($ivaPagado > 0.01);

$dfPrevios = json_decode($venta['FiscalJSON'], true) ?? [];

$sqlDet = "SELECT * FROM `$idUser-Ventas_Detalle` WHERE ID_Venta = '{$venta['ID_Venta']}'";
$items = $db->obtenerDatos($sqlDet)['data'] ?? [];

// 4. MAPEÓ DE FORMA DE PAGO SAT
$metodo = strtolower($venta['Metodo_Pago']);
$formaPagoSAT = "01"; // Efectivo por defecto
if(strpos($metodo, 'tarjeta') !== false) $formaPagoSAT = "04";
if(strpos($metodo, 'transferencia') !== false) $formaPagoSAT = "03";
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comprobante Oficial | <?php echo $folio; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root { --primary: #4f46e5; --danger: #ef4444; --dark: #0f172a; --bg: #f8fafc; }
        body { background-color: var(--bg); font-family: 'Plus Jakarta Sans', sans-serif; padding: 20px 0; }
        .ticket-card { max-width: 550px; margin: auto; background: white; border-radius: 40px; box-shadow: 0 30px 60px rgba(0,0,0,0.12); border: none; overflow: hidden; }
        .header-vibrant { background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: white; padding: 50px 30px; text-align: center; border-bottom: 5px solid var(--primary); }
        .price-banner { background: white; border-radius: 30px; padding: 25px; text-align: center; margin: -40px 35px 30px; border: 1px solid #e2e8f0; box-shadow: 0 15px 35px rgba(0,0,0,0.1); }
        .price-total { font-size: 52px; font-weight: 800; color: var(--primary); letter-spacing: -2px; }
        .totals-section { background: #f8fafc; border-radius: 25px; padding: 25px; border: 1px solid #edf2f7; }
        .alert-fiscal { background: #fff1f2; border: 1px solid #fecaca; border-radius: 15px; padding: 15px; color: #991b1b; font-size: 13px; font-weight: 600; }
        .btn-premium { border-radius: 20px; font-weight: 700; padding: 16px; transition: 0.4s; border: none; }
        .input-premium { border-radius: 15px; border: 2px solid #f1f5f9; padding: 12px; font-weight: 600; }
        @media print { .no-print { display: none !important; } .ticket-card { box-shadow: none; margin: 0; width: 100%; border-radius: 0; } }
    </style>
</head>
<body>

<div class="container">
    <div class="ticket-card">
        <div class="header-vibrant">
            <h3 class="fw-800 mb-1">Resumen de Pago</h3>
            <p class="opacity-75 small fw-bold">TICKET: <?php echo $folio; ?> | <?php echo date('d/m/Y', strtotime($venta['Fecha'])); ?></p>
        </div>

        <div class="price-banner">
            <div class="price-total">$<?php echo number_format($venta['Total'], 2); ?></div>
            <div class="badge bg-primary rounded-pill px-3 py-2 mt-2"><?php echo strtoupper($venta['Metodo_Pago'] ?? 'EFECTIVO'); ?></div>
        </div>

        <div class="px-4 pb-5">
            <div class="mb-4 p-3 rounded-4 bg-light border border-white">
                <h6 class="fw-800 small text-muted text-uppercase mb-2">Cliente / Socio</h6>
                <div class="fw-bold fs-5"><?php echo $venta['ClienteNom']; ?></div>
                <div class="small text-muted mt-1">
                    <i class="fas fa-envelope me-2 text-primary"></i><?php echo $venta['ClienteEmail']; ?><br>
                    <i class="fas fa-phone me-2 text-primary"></i><?php echo $venta['ClienteTel']; ?>
                </div>
            </div>

            <div class="mb-4">
                <?php foreach($items as $it): ?>
                <div class="d-flex justify-content-between align-items-center py-2 border-bottom border-light">
                    <div class="small fw-bold text-dark"><?php echo (int)$it['Cantidad']; ?> x <?php echo $it['Nombre_Producto']; ?></div>
                    <div class="fw-bold text-muted">$<?php echo number_format($it['Subtotal'], 2); ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="totals-section mb-4">
                <div class="d-flex justify-content-between mb-2">
                    <span class="small fw-bold text-muted">SUBTOTAL</span>
                    <span class="fw-bold">$<?php echo number_format($venta['Subtotal'], 2); ?></span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span class="small fw-bold text-muted">I.V.A (16%)</span>
                    <span class="fw-bold <?php echo $tieneIVA ? 'text-dark' : 'text-danger'; ?>">
                        $<?php echo number_format($ivaPagado, 2); ?>
                    </span>
                </div>
                <div class="d-flex justify-content-between pt-3 border-top border-2 border-white">
                    <span class="h4 fw-800 mb-0">TOTAL</span>
                    <span class="h4 fw-800 mb-0 text-primary">$<?php echo number_format($venta['Total'], 2); ?></span>
                </div>
            </div>

            <?php if(!$tieneIVA): ?>
            <div class="alert-fiscal mb-4">
                <i class="fas fa-exclamation-triangle me-2"></i>
                Este ticket no incluye IVA. No es posible generar factura fiscal.
            </div>
            <?php endif; ?>

            <div class="d-grid gap-3 no-print">
                <button class="btn btn-premium btn-success text-white shadow" onclick="enviarWA()">
                    <i class="fab fa-whatsapp me-2 fa-lg"></i> ENVIAR WHATSAPP
                </button>
                <div class="row g-2">
                    <div class="col-6"><button class="btn btn-premium btn-dark w-100" onclick="window.print()">TICKET</button></div>
                    <div class="col-6">
                        <?php if($yaSolicitado): ?>
                            <button class="btn btn-premium btn-secondary w-100" disabled>SOLICITADA</button>
                        <?php else: ?>
                            <button class="btn btn-premium btn-primary w-100" 
                                    <?php echo $tieneIVA ? 'data-bs-toggle="modal" data-bs-target="#modalCFDI"' : 'onclick="errorIVA()"'; ?>>
                                FACTURAR
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
                <button class="btn btn-link text-muted small fw-bold text-decoration-none mt-2" data-bs-toggle="modal" data-bs-target="#modalTerms">Términos y Condiciones.</button>
				<button class="btn btn-link text-muted small fw-bold text-decoration-none mt-2" data-bs-toggle="modal" data-bs-target="#modalAviso">Aviso de Privacidad.</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCFDI" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-pro p-3 border-0 shadow-lg" style="border-radius:30px;">
            <div class="modal-header border-0 pb-0">
                <h5 class="fw-800">Solicitud de Factura CFDI 4.0</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="formCFDI" class="row g-3">
                    <div class="col-12">
                        <label class="fw-bold small text-muted">RAZÓN SOCIAL (EXACTO SAT)</label>
                        <input type="text" id="f_razon" class="form-control input-premium" value="<?php echo $dfPrevios['razon'] ?? strtoupper($venta['ClienteNom']); ?>">
                    </div>
                    <div class="col-md-7">
                        <label class="fw-bold small text-muted">RFC</label>
                        <input type="text" id="f_rfc" class="form-control input-premium" maxlength="13" value="<?php echo $dfPrevios['rfc'] ?? ''; ?>">
                    </div>
                    <div class="col-md-5">
                        <label class="fw-bold small text-muted">C.P. FISCAL</label>
                        <input type="text" id="f_cp" class="form-control input-premium" maxlength="5" value="<?php echo $dfPrevios['cp'] ?? ''; ?>">
                    </div>
                    <div class="col-12">
                        <label class="fw-bold small text-muted">RÉGIMEN FISCAL</label>
                        <select id="f_regimen" class="form-select input-premium">
                            <option value="601" <?php echo ($dfPrevios['regimen'] ?? '') == '601' ? 'selected' : ''; ?>>601 - General de Ley Personas Morales</option>
                            <option value="605" <?php echo ($dfPrevios['regimen'] ?? '') == '605' ? 'selected' : ''; ?>>605 - Sueldos e Ingresos Asimilados</option>
                            <option value="612" <?php echo ($dfPrevios['regimen'] ?? '') == '612' ? 'selected' : ''; ?>>612 - Personas Físicas con Actividades Prof.</option>
                            <option value="626" <?php echo ($dfPrevios['regimen'] ?? '') == '626' ? 'selected' : ''; ?>>626 - RESICO</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="fw-bold small text-muted">USO CFDI</label>
                        <select id="f_uso" class="form-select input-premium">
                            <option value="G03">G03 - Gastos en general</option>
                            <option value="S01">S01 - Sin efectos fiscales</option>
                            <option value="CP01">CP01 - Pagos</option>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="fw-bold small text-muted">EMAIL ENVÍO</label>
                        <input type="email" id="c_email" class="form-control input-premium" value="<?php echo $venta['ClienteEmail']; ?>">
                    </div>
                    <div class="col-6">
                        <label class="fw-bold small text-muted">TELÉFONO</label>
                        <input type="text" id="c_tel" class="form-control input-premium" value="<?php echo $venta['ClienteTel']; ?>">
                    </div>
                    <button type="button" onclick="validarYEnviar()" id="btnF" class="btn btn-premium btn-primary w-100 mt-4 shadow py-3">GENERAR SOLICITUD</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalTerms" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 p-4 shadow-lg" style="border-radius:30px;">
            <h5 class="fw-800 mb-3"><i class="fas fa-file-contract text-warning me-2"></i>Términos de Servicio</h5>
            <div class="small text-muted">
                <p>1. <b>Facturación:</b> Solo tickets con IVA.</p>
                <p>2. <b>Plazos:</b> Se procesan en un lapso de 24 a 48 horas.</p>
            </div>
            <button class="btn btn-dark w-100 rounded-pill mt-4 fw-bold" data-bs-dismiss="modal">CERRAR</button>
        </div>
    </div>
</div>
	
<div class="modal fade" id="modalAviso" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 p-4 shadow-lg" style="border-radius:30px;">
            <h5 class="fw-800 mb-3"><i class="fas fa-file-contract text-warning me-2"></i>Aviso de Privasidad</h5>
            <div class="small text-muted">
                <p>1. <b>Facturación:</b> Solo tickets con IVA.</p>
                <p>2. <b>Plazos:</b> Se procesan en un lapso de 24 a 48 horas.</p>
            </div>
            <button class="btn btn-dark w-100 rounded-pill mt-4 fw-bold" data-bs-dismiss="modal">CERRAR</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const VENTA = {
    id: "<?php echo $venta['ID_Venta']; ?>",
    idc: "<?php echo $venta['IDC']; ?>",
    idu: "<?php echo $venta['IDU_Usuario']; ?>",
    forma: "<?php echo $formaPagoSAT; ?>"
};

function errorIVA() {
    Swal.fire('IVA no pagado', 'Este ticket no incluye impuestos desglosados.', 'error');
}

async function validarYEnviar() {
    const btn = document.getElementById('btnF');
    const datos = {
        razon: document.getElementById('f_razon').value.toUpperCase().trim(),
        rfc: document.getElementById('f_rfc').value.toUpperCase().trim(),
        cp: document.getElementById('f_cp').value.trim(),
        regimen: document.getElementById('f_regimen').value,
        uso: document.getElementById('f_uso').value,
        email: document.getElementById('c_email').value.trim(),
        tel: document.getElementById('c_tel').value.trim()
    };

    if(datos.rfc.length < 12 || datos.cp.length < 5) return Swal.fire('Error', 'RFC o CP inválido.', 'warning');

    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Guardando...';

    const snapshot = JSON.stringify(datos).replace(/'/g, "''");

    // 1. Actualizar datos del cliente para futuras compras
    const sqlCli = `UPDATE \`<?php echo $idUser;?>-Clientes\` SET Email='${datos.email}', Telefono='${datos.tel}', Datos_Fiscales='${snapshot}' WHERE IDC=${VENTA.idc}`;
    
    // 2. Insertar solicitud de facturación (Tabla correcta del esquema)
    const sqlSol = `INSERT INTO \`<?php echo $idUser;?>-Facturacion_Solicitudes\` 
                    (ID_Venta, IDC_Cliente, IDU_Usuario, Uso_CFDI, Metodo_Pago, Forma_Pago, Datos_Fiscales_Snapshot, Estado) 
                    VALUES 
                    (${VENTA.id}, ${VENTA.idc}, '${VENTA.idu}', '${datos.uso}', 'PUE', '${VENTA.forma}', '${snapshot}', 'Pendiente')`;

    try {
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `db=MS_Datos&sql=${encodeURIComponent(sqlCli)}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} });
        
        const res = await fetch('../librerias/AJAX/Execute.php', { 
            method: 'POST', 
            body: `db=MS_Datos&sql=${encodeURIComponent(sqlSol)}`, 
            headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
        }).then(r => r.json());

        if(res.status === 'success' || res.last_id) {
            Swal.fire('¡Éxito!', 'Solicitud registrada correctamente.', 'success').then(() => location.reload());
        } else {
            throw new Error();
        }
    } catch(e) {
        Swal.fire('Error', 'No se pudo guardar en la base de datos.', 'error');
        btn.disabled = false;
        btn.innerHTML = 'GENERAR SOLICITUD';
    }
}

function enviarWA() {
    const url = encodeURIComponent(window.location.href);
    window.open(`https://wa.me/52<?php echo $venta['ClienteTel']; ?>?text=Hola, te comparto tu ticket digital: ${url}`, '_blank');
}
</script>
</body>
</html>