<?php
require_once 'config.php';
session_start();
if (!isset($_SESSION['admin_auth'])) { http_response_code(403); exit('No autorizado'); }

$id = (int)($_GET['id'] ?? 0);
if (!$id) { exit('ID requerido'); }

$db = getDB();
$stmt = $db->prepare("SELECT * FROM productos WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$producto = $stmt->get_result()->fetch_assoc();
$stmt->close();
$db->close();

if (!$producto) { exit('Producto no encontrado'); }

$slug = $producto['slug'];
$precio = number_format($producto['precio'], 0, '', '');

$codigo = <<<'VBACODE'
Private Const PROD As String = "{{SLUG}}"
Private Const SAL As String = "{{SALT}}"
Private Const PRE As String = "{{PRECIO}}"
Private Const URLB As String = "https://e.taxlawbolivia.com/licenciasexcel/"
Private Const PW As String = "4804"
Private yaAviso As Boolean

Private Sub Workbook_Open()
    If Activado() Then
        AbrirHojas
    Else
        CerrarHojas
        MsgBox "Archivo protegido." & vbCrLf & "Haz clic en cualquier celda para activar.", vbInformation, "boliviaimpuestos.com"
    End If
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    If Activado() Then Exit Sub
    If yaAviso Then Exit Sub
    yaAviso = True
    Dim pc As String
    pc = Left(Environ("COMPUTERNAME"), 8)
    Dim obj As Object
    Set obj = CreateObject("WScript.Shell")
    obj.Run URLB & "?producto=" & PROD & "&pc=" & pc & "&precio=" & PRE
    Dim c As String
    c = InputBox("1. Paga en la pagina web" & vbCrLf & "2. Ingresa la contrasena:", "boliviaimpuestos.com")
    If c = "" Then
        yaAviso = False
        Exit Sub
    End If
    If LCase(Trim(c)) = LCase(HacerClave(pc)) Then
        On Error Resume Next
        ThisWorkbook.Names("BIBK").Delete
        On Error GoTo 0
        ThisWorkbook.Names.Add Name:="BIBK", RefersTo:="=""" & c & """", Visible:=False
        ThisWorkbook.Save
        AbrirHojas
        MsgBox "Activado!", vbInformation
    Else
        MsgBox "Contrasena incorrecta.", vbCritical
        yaAviso = False
    End If
End Sub

Private Function Activado() As Boolean
    On Error GoTo NoHay
    Dim v As String
    v = ThisWorkbook.Names("BIBK").RefersTo
    v = Replace(Replace(v, "=""", ""), """", "")
    Dim pc As String
    pc = Left(Environ("COMPUTERNAME"), 8)
    Activado = (LCase(v) = LCase(HacerClave(pc)))
    Exit Function
NoHay:
    Activado = False
End Function

Private Function HacerClave(pc As String) As String
    Dim s As String
    s = pc & PROD & SAL
    Dim h1 As Long
    Dim h2 As Long
    h1 = 5381
    h2 = 7919
    Dim i As Long
    For i = 1 To Len(s)
        h1 = (h1 * 33 + Asc(Mid(s, i, 1))) Mod 65536
        h2 = (h2 * 37 + Asc(Mid(s, i, 1))) Mod 65536
    Next i
    HacerClave = LCase(Right("0000" & Hex(h1), 4) & Right("0000" & Hex(h2), 4))
End Function

Private Sub CerrarHojas()
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        On Error Resume Next
        ws.Unprotect Password:=PW
        ws.Protect Password:=PW
        On Error GoTo 0
    Next ws
End Sub

Private Sub AbrirHojas()
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        On Error Resume Next
        ws.Unprotect Password:=PW
        On Error GoTo 0
    Next ws
End Sub
VBACODE;

$codigo = str_replace(['{{SLUG}}', '{{PRECIO}}', '{{SALT}}'], [$slug, $precio, SALT_SECRETO], $codigo);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>VBA - <?= htmlspecialchars($slug) ?></title>
    <style>
        *{box-sizing:border-box}
        body{font-family:'Segoe UI',sans-serif;background:#f0f2f5;padding:20px;margin:0}
        .container{max-width:900px;margin:0 auto}
        h1{font-size:20px;color:#333}
        .step{background:#fff;border-radius:10px;padding:20px;margin-bottom:16px;box-shadow:0 1px 4px rgba(0,0,0,.08)}
        .step h2{font-size:16px;color:#2980b9;margin-top:0}
        .step-num{display:inline-block;background:#2980b9;color:#fff;width:28px;height:28px;border-radius:50%;text-align:center;line-height:28px;font-weight:bold;font-size:14px;margin-right:8px}
        .step-num.prep{background:#e67e22}
        .code-box{position:relative;background:#1e1e1e;color:#d4d4d4;border-radius:8px;padding:16px;font-family:'Courier New',monospace;font-size:12px;white-space:pre;overflow-x:auto;max-height:400px;overflow-y:auto;line-height:1.4}
        .copy-btn{position:absolute;top:8px;right:8px;background:#27ae60;color:#fff;border:none;padding:6px 14px;border-radius:6px;cursor:pointer;font-size:12px;font-weight:600;z-index:2}
        .copy-btn:hover{background:#1e8449}
        .copy-btn.copied{background:#888}
        .warn{background:#fff3cd;border:1px solid #ffc107;border-radius:8px;padding:12px;font-size:13px;color:#856404;margin:12px 0}
        .success{background:#d4edda;border:1px solid #28a745;border-radius:8px;padding:12px;font-size:13px;color:#155724;margin:12px 0}
        .back{display:inline-block;margin-bottom:16px;color:#2980b9;text-decoration:none;font-size:13px}
        ol.sheet-steps{margin:8px 0;padding-left:20px}
        ol.sheet-steps li{margin-bottom:6px;font-size:14px}
    </style>
</head>
<body>
<div class="container">
    <a href="admin.php" class="back">&larr; Volver al admin</a>
    <h1>Proteger: <?= htmlspecialchars($producto['nombre']) ?></h1>

    <div class="warn">
        <b>Importante:</b> Sigue los pasos en orden. El paso 1 es obligatorio para que el archivo quede protegido incluso si el usuario no habilita macros.
    </div>

    <div class="step">
        <h2><span class="step-num prep">1</span> Proteger cada hoja del Excel</h2>
        <p>Antes de tocar el VBA, protege las hojas desde Excel:</p>
        <ol class="sheet-steps">
            <li>Abre tu archivo <code>.xlsm</code> en Excel</li>
            <li>Ve a la <b>primera hoja</b></li>
            <li>Menu <b>Revisar &rarr; Proteger hoja</b></li>
            <li>Escribe la contrasena: <code>4804</code> &rarr; Aceptar &rarr; Confirmar <code>4804</code></li>
            <li><b>Repite</b> para TODAS las hojas del archivo</li>
            <li>Guarda el archivo</li>
        </ol>
        <div class="warn" style="margin-top:12px">
            Sin este paso, cualquier persona que descargue el Excel y no habilite macros podra editar libremente las celdas.
        </div>
    </div>

    <div class="step">
        <h2><span class="step-num">2</span> Abrir el editor VBA: Alt + F11</h2>
        <p>En el panel izquierdo, doble clic en <b>ThisWorkbook</b>.</p>
        <p>Pega TODO este codigo:</p>
        <div style="position:relative">
            <button class="copy-btn" onclick="copiar('cod')">Copiar</button>
            <div class="code-box" id="cod"><?= htmlspecialchars($codigo) ?></div>
        </div>
    </div>

    <div class="step">
        <h2><span class="step-num">3</span> Proteger el codigo VBA</h2>
        <p><b>Herramientas &rarr; Propiedades de VBAProject &rarr;</b> pestana <b>Proteccion</b></p>
        <p>Marca <b>"Bloquear proyecto"</b>, contrasena: <code>4804</code></p>
    </div>

    <div class="step">
        <h2><span class="step-num">4</span> Guardar y subir</h2>
        <ol class="sheet-steps">
            <li>Cierra VBA (Alt+F11)</li>
            <li><b>Guardar como</b> &rarr; tipo <b>"Libro habilitado para macros (.xlsm)"</b></li>
            <li>Sube el archivo al admin con el boton <b>"Subir .xlsm"</b></li>
        </ol>
    </div>

    <div class="success">
        <b>Prueba final:</b> Cierra y vuelve a abrir el archivo.
        <br>Debe salir el mensaje "Archivo protegido. Haz clic en cualquier celda para activar."
        <br>Si ves barra amarilla "Habilitar contenido", haz clic ahi primero.
        <br><br>
        <b>Sin macros:</b> Las celdas estan bloqueadas (no se pueden editar).
        <br><b>Con macros:</b> Al hacer clic en cualquier celda se abre la pagina de pago.
    </div>
</div>
<script>
function copiar(id) {
    const el = document.getElementById(id);
    const btn = el.parentElement.querySelector('.copy-btn');
    navigator.clipboard.writeText(el.textContent).then(() => {
        btn.textContent = 'Copiado!';
        btn.classList.add('copied');
        setTimeout(() => { btn.textContent = 'Copiar'; btn.classList.remove('copied'); }, 2000);
    });
}
</script>
</body>
</html>
