<?php
require_once 'config.php';

// Validate and sanitize filename
$filename = isset($_GET['filename']) ? sanitizeInput($_GET['filename']) : '';
$token = isset($_GET['token']) ? sanitizeInput($_GET['token']) : '';

if (empty($filename) || empty($token)) {
    die('Invalid parameters');
}

// Check if it's a request to save signature position
if (isset($_POST['save_signature'])) {
    $signatureData = $_POST['signature_data'];
    $posX = $_POST['pos_x'];
    $posY = $_POST['pos_y'];
    
    // Save the signature data and position to the database
    $stmt = $db->prepare("UPDATE firmas SET signature_data = ?, pos_x = ?, pos_y = ? WHERE token = ?");
    $stmt->bind_param('sdds', $signatureData, $posX, $posY, $token);
    $stmt->execute();
    exit();
}

// Verify token matches file
$db = getDatabaseConnection();
$stmt = $db->prepare("SELECT id_de_documento FROM firmas WHERE token = ? AND nombre_de_archivo = ? AND estado_de_documento = 'valido'");
$stmt->bind_param('ss', $token, $filename);
$stmt->execute();
$result = $stmt->get_result();

if (!$result->fetch_assoc()) {
    die('Invalid document access');
}

// Set the path to the signed documents directory
$filepath = __DIR__ . '/signed_documents/' . $filename;

// Validate that file exists and is within the signed_documents directory
if (!file_exists($filepath) || !is_file($filepath) || 
    dirname(realpath($filepath)) !== realpath(__DIR__ . '/signed_documents')) {
    die('Invalid file access');
} 

// Calculate file hash for tampering detection
$fileHash = hash_file('sha256', $filepath);

// Expose document hash for integrity checks
header('X-Document-Hash: ' . $fileHash);

// If raw PDF is requested, stream it directly
if (isset($_GET['raw']) && $_GET['raw'] === '1') {
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="' . basename($filename) . '"');
    header('Content-Length: ' . filesize($filepath));
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    readfile($filepath);
    exit;
}

// We're embedding the document in an HTML page below — do not send PDF or framing headers here
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <title>Firmador Codex Documentos PDF</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            padding-bottom: 100px;
            font-family: Arial, sans-serif;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
            #signature-pad {
                position: fixed;
                bottom: 100px;
                left: 50%;
                transform: translateX(-50%);
                background: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
                z-index: 1000;
                display: none;
            }
            #signature-canvas {
                border: 1px solid #ccc;
                border-radius: 4px;
                background: white;
                cursor: crosshair;
            }
            .signature-placeholder {
                position: absolute;
                border: 2px dashed #2B6CB0;
                background: rgba(43, 108, 176, 0.1);
                padding: 20px;
                cursor: move;
                display: none;
            }
        
        .app-header {
            background-color: white;
            border-bottom: 1px solid #ddd;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .title-section {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .title-section img {
            width: 24px;
            height: 24px;
        }
        
        .blue-bar {
            background-color: #2B6CB0;
            color: white;
            padding: 15px;
            text-align: center;
        }
        
        .main-content {
            flex: 1;
            padding: 20px;
            background-color: #f8f9fa;
        }
        
        .upload-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .upload-title {
            margin: 0 0 15px 0;
            font-size: 1.2em;
        }
        
        .file-buttons {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .btn {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            cursor: pointer;
        }
        
        .btn-primary {
            background-color: #2B6CB0;
            color: white;
            border: none;
        }
        
        .file-size {
            color: #666;
            font-size: 0.9em;
        }
        
        .toolbar {
            display: flex;
            gap: 10px;
            margin: 20px 0;
        }
        
        .document-area {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            min-height: 500px;
            padding: 20px;
        }
        
        .signature-controls {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
        }
        .header {
            background-color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e2e8f0;
        }
        .header-title {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2d3748;
        }
        .header-right {
            display: flex;
            gap: 0.5rem;
        }
        .header-button {
            padding: 0.5rem 1rem;
            border-radius: 4px;
            border: 1px solid #cbd5e0;
            background: white;
            color: #4a5568;
            cursor: pointer;
            font-size: 0.875rem;
        }
        .header-button:hover {
            background: #f7fafc;
        }
        .subheader {
            background-color: #2b6cb0;
            color: white;
            padding: 1rem 2rem;
            text-align: center;
        }
        .main-content {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .upload-section {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        .upload-section h2 {
            margin: 0 0 1rem 0;
            color: #2d3748;
        }
        .file-upload {
            display: flex;
            gap: 1rem;
            align-items: center;
            margin-bottom: 1rem;
        }
        .choose-file, .select-pdf {
            padding: 0.5rem 1rem;
            border: 1px solid #cbd5e0;
            border-radius: 4px;
            background: white;
            color: #4a5568;
            cursor: pointer;
        }
        .file-info {
            color: #718096;
            font-size: 0.875rem;
        }
        .navigation {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 1rem;
            margin-bottom: 2rem;
        }
        .nav-button {
            padding: 0.5rem 1rem;
            border: 1px solid #cbd5e0;
            border-radius: 4px;
            background: white;
            color: #4a5568;
            cursor: pointer;
        }
        .document-actions {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
        }
        .action-button {
            padding: 0.5rem 1rem;
            border: 1px solid #cbd5e0;
            border-radius: 4px;
            background: white;
            color: #4a5568;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .action-button:hover {
            background: #f7fafc;
        }
        .page-container {
            max-width: 816px; /* US Letter width */
            margin: 40px auto;
            padding: 40px;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            min-height: 1056px; /* US Letter height */
            position: relative;
            box-sizing: border-box;
        }
        .signature-container {
            position: relative;
            width: 100%;
            background-color: #f5f5f5;
            min-height: 100vh;
            padding: 20px;
            box-sizing: border-box;
        }
        #pdf-viewer {
            width: 100%;
            height: 100%;
            border: none;
            background: white;
        }
        .letter-content {
            font-family: Arial, sans-serif;
            font-size: 12pt;
            line-height: 1.5;
            color: #333;
        }
        .letter-header {
            text-align: right;
            margin-bottom: 40px;
        }
        .letter-body {
            margin-bottom: 40px;
        }
        .letter-footer {
            margin-top: 40px;
        }
        #signature-pad {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            border: 2px solid #0066cc;
            border-radius: 8px;
            padding: 15px;
            z-index: 1000;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            text-align: center;
            display: none;
        }
        #signature-canvas {
            border: 1px solid #ccc;
            background-color: #fff;
            margin-bottom: 10px;
            cursor: crosshair;
        }
        .signature-image {
            position: absolute;
            cursor: move;
            max-width: 200px;
            display: none;
            border: 1px dashed #0066cc;
        }
        .controls {
            margin-top: 10px;
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        .controls button {
            padding: 8px 15px;
            background-color: #0066cc;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .controls button:hover {
            background-color: #0052a3;
        }
        #clear-signature {
            background-color: #dc3545;
        }
        #clear-signature:hover {
            background-color: #bd2130;
        }
    </style>
</head>
<body>
    <div class="app-header">
        <div class="title-section">
            <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%232B6CB0' d='M12 2L4 6v12l8 4 8-4V6l-8-4zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z'/%3E%3C/svg%3E" alt="PDF icon">
            <h1 style="margin: 0; font-size: 1.2em;">Firmador Codex Documentos PDF</h1>
        </div>
        <div>
            <button class="btn">Choose</button>
            <button class="btn">Draw</button>
        </div>
    </div>
    <!-- Quick debug button to open signature pad (remove in production) -->
    <button id="debug-open-pad" style="position:fixed; right:18px; top:86px; z-index:2000; padding:8px 10px; background:#2B6CB0; color:#fff; border:none; border-radius:6px;">Abrir Firma</button>
    
    <div class="blue-bar">
        Cargue su documento, fírmelo digitalmente y obtenga verificación segura
    </div>

    <div class="main-content">
        <div class="upload-container">
            <h2 class="upload-title">Cargar Documento PDF</h2>
            <div class="file-buttons">
                <button class="btn">Choose File</button>
                <span>No file chosen</span>
                <button class="btn btn-primary">Seleccionar PDF</button>
            </div>
            <div class="file-size">Tamaño máximo: 10MB</div>
        </div>

        <div class="toolbar">
            <button class="btn">← Anterior</button>
            <span>Página 1 de 1</span>
            <button class="btn">Siguiente →</button>
        </div>



        <div class="document-area" id="pdf-container">
        <div class="navigation">
            <button class="nav-button">← Anterior</button>
            <span>Página 1 de 1</span>
            <button class="nav-button">Siguiente →</button>
        </div>

        <div id="pdf-content">
            <iframe
                src="<?php echo htmlspecialchars(
                    'view_document?filename=' . urlencode($filename) .
                    '&token=' . urlencode($token) .
                    '&raw=1'
                ); ?>"
                width="100%"
                height="800px"
                style="border: none;"
            ></iframe>
        </div>
    </div>

    <div class="document-viewer">
            <div class="letter-header">
                <div>[Your Name]</div>
                <div>[Your Address]</div>
                <div>[City, State ZIP Code]</div>
                <div>[Email Address]</div>
                <div>[Phone Number]</div>
                <div>[Date]</div>
            </div>
            
            <div class="letter-body">
                <div>Customer Service Department</div>
                <div>[Current Energy Company]</div>
                <div>[Company Address]</div>
                <div>[City, State ZIP Code]</div>
                <br>
                <div>Subject: [Your Subject]</div>
                <br>
                <div>Dear Sir/Madam,</div>
                <br>
                <div>[Your Letter Content]</div>
            </div>
            
            <div class="letter-footer">
                <div>Sincerely,</div>
                <br>
                <div style="min-height: 60px;" id="signature-area"></div>
                <div>[Your Name]</div>
            </div>
        </div>
        
        <!-- single consolidated signature pad (hidden by default) -->
        <div id="signature-pad" style="display:none; position:fixed; bottom:80px; left:50%; transform:translateX(-50%); z-index:1000; background:#fff; padding:14px; border-radius:8px; box-shadow:0 6px 20px rgba(0,0,0,0.12);">
            <canvas id="signature-canvas" width="400" height="200" style="border:1px solid #ddd; border-radius:6px; background:#fff; display:block;"></canvas>
            <div class="controls" style="margin-top:10px; display:flex; gap:8px; justify-content:center;">
                <button id="save-signature" class="btn">Guardar Firma</button>
                <button id="clear-signature" class="btn">Limpiar</button>
                <button id="close-signature" class="btn">Cerrar</button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const canvas = document.getElementById('signature-canvas');
            const ctx = canvas.getContext('2d');
            const pad = document.getElementById('signature-pad');
            let drawing = false;
            let last = { x: 0, y: 0 };
            let savedImage = null; // Image element for placed signature

            // pointer drawing (works for mouse and touch)
            function getPos(e) {
                const r = canvas.getBoundingClientRect();
                const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                const clientY = e.touches ? e.touches[0].clientY : e.clientY;
                return { x: clientX - r.left, y: clientY - r.top };
            }

            function start(e) {
                e.preventDefault();
                drawing = true;
                const p = getPos(e);
                last.x = p.x; last.y = p.y;
                ctx.beginPath(); ctx.moveTo(last.x, last.y);
            }

            function move(e) {
                if (!drawing) return;
                e.preventDefault();
                const p = getPos(e);
                ctx.lineWidth = 2; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.strokeStyle = '#000';
                ctx.beginPath(); ctx.moveTo(last.x, last.y); ctx.lineTo(p.x, p.y); ctx.stroke();
                last.x = p.x; last.y = p.y;
            }

            function end(e) {
                if (!drawing) return;
                e.preventDefault();
                drawing = false;
            }

            // prevent touch scrolling while drawing
            canvas.style.touchAction = 'none';
            canvas.addEventListener('pointerdown', start);
            canvas.addEventListener('pointermove', move);
            canvas.addEventListener('pointerup', end);
            canvas.addEventListener('pointercancel', end);
            canvas.addEventListener('pointerleave', end);

            // helper to find a button by visible text (robust across markup)
            function findButtonByText(text) {
                const nodes = Array.from(document.querySelectorAll('button'));
                return nodes.find(b => b.textContent && b.textContent.replace(/\s+/g,' ').trim().includes(text));
            }

            // show pad when user clicks the visible 'Limpiar Firma' button
            const clearBtn = findButtonByText('Limpiar Firma') || document.getElementById('clearSignature');
            if (clearBtn) {
                clearBtn.addEventListener('click', function () {
                    // clear canvas and show pad
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    if (pad) pad.style.display = 'block';
                });
            }

            // Save / place signature when user clicks the visible 'Guardar y Firmar' button
            const saveDocBtn = findButtonByText('Guardar y Firmar') || document.getElementById('saveDocument');
            if (saveDocBtn) {
                saveDocBtn.addEventListener('click', function () {
                    if (!pad || pad.style.display === 'none') {
                        // nothing to do here (user might be using other workflow)
                        return;
                    }

                    // check if canvas has content
                    const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
                    const isEmpty = !imgData.some(v => v !== 0);
                    if (isEmpty) {
                        alert('Por favor dibuje una firma antes de guardar.');
                        return;
                    }

                    const dataUrl = canvas.toDataURL('image/png');

                    // create draggable image placed over the document area 
                    if (savedImage) savedImage.remove();
                    savedImage = new Image();
                    savedImage.src = dataUrl;
                    savedImage.style.position = 'absolute';
                    savedImage.style.left = '50px';
                    savedImage.style.top = '200px';
                    savedImage.style.maxWidth = '240px';
                    savedImage.style.cursor = 'move';
                    savedImage.className = 'signature-image';

                    // append to pdf container if present, otherwise to body
                    const container = document.getElementById('pdf-container') || document.body;
                    // ensure container is positioned for absolute children
                    const cs = window.getComputedStyle(container);
                    if (cs.position === 'static') container.style.position = 'relative';
                    container.appendChild(savedImage);

                    makeDraggableWithin(savedImage, container);

                    // hide pad after placing
                    pad.style.display = 'none';

                    // send data to server to save signature for this token
                    fetch('save_signature.php', {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ signature_data: dataUrl, token: '<?php echo urlencode($token); ?>' })
                    }).catch(err => console.warn('save_signature failed', err));
                });
            } 

            // pad controls
            const padSave = document.getElementById('save-signature');
            const padClear = document.getElementById('clear-signature');
            const padClose = document.getElementById('close-signature');
            if (padClear) padClear.addEventListener('click', () => ctx.clearRect(0, 0, canvas.width, canvas.height));
            if (padClose) padClose.addEventListener('click', () => { if (pad) pad.style.display = 'none'; });
            if (padSave) padSave.addEventListener('click', () => { if (saveDocBtn) saveDocBtn.click(); });

            // debug button
            const debugOpen = document.getElementById('debug-open-pad');
            if (debugOpen) debugOpen.addEventListener('click', () => { if (pad) pad.style.display = 'block'; });

            // draggable helper constrained to parent
            function makeDraggableWithin(el, parent) {
                let dragging = false, sx = 0, sy = 0, ox = 0, oy = 0;
                el.addEventListener('mousedown', function (e) {
                    dragging = true; sx = e.clientX; sy = e.clientY;
                    const re
