<?php
declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';

// For contract signing, we don't require authentication
// Clients should be able to sign contracts without logging in

// Initialize tenant context (if possible, but don't require it)
TenantManager::initialize();
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Contract.php';
require_once __DIR__ . '/../src/ActivityLog.php';

$token = $_GET['token'] ?? '';
$contract = null;
$error = '';
$success = '';
$workspaceCompanyName = null;

if ($token) {
    $contract = Contract::findByToken($token);
    if (!$contract) {
        $error = 'Invalid or expired signing link.';
    } else {
        // Extract workspace from contract for download links
        if (!isset($_GET['workspace']) && $contract['company_id']) {
            $pdo = getPDO();
            $stmt = $pdo->prepare("SELECT username, name FROM companies WHERE id = ?");
            $stmt->execute([$contract['company_id']]);
            $company = $stmt->fetch();
            if ($company) {
                $_GET['workspace'] = $company['username'];
                $workspaceCompanyName = $company['name'] ?? null;
            }
        } elseif ($contract['company_id']) {
            $pdo = getPDO();
            $stmt = $pdo->prepare("SELECT name FROM companies WHERE id = ?");
            $stmt->execute([$contract['company_id']]);
            $company = $stmt->fetch();
            $workspaceCompanyName = $company['name'] ?? null;
        }
    }
}

// Handle signature submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $contract) {
    $signatureType = $_POST['signature_type'] ?? '';
    $signatureData = $_POST['signature_data'] ?? '';
    $signerName = $_POST['signer_name'] ?? '';
    
    if (empty($signatureData) || empty($signerName)) {
        $error = 'Please provide your signature and name.';
    } else {
        $updateData = [
            $signatureType . '_signature_data' => json_encode([
                'signature' => $signatureData,
                'name' => $signerName,
                'ip' => $_SERVER['REMOTE_ADDR'],
                'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                'timestamp' => date('Y-m-d H:i:s')
            ]),
            $signatureType . '_signed_at' => date('Y-m-d H:i:s'),
            $signatureType . '_ip' => $_SERVER['REMOTE_ADDR'],
            $signatureType . '_user_agent' => $_SERVER['HTTP_USER_AGENT'],
        ];
        
        Contract::update((int) $contract['id'], $updateData);
        
        // Regenerate PDF with new signature (automatically increments version)
        try {
            Contract::generatePdf((int) $contract['id'], null, $_GET['workspace'] ?? null);
        } catch (Exception $e) {
            error_log('PDF regeneration failed after signing: ' . $e->getMessage());
        }
        
        // Check if both parties have signed
        $updatedContract = Contract::find((int) $contract['id']);
        if ($updatedContract['client_signed_at'] && $updatedContract['internal_signed_at']) {
            $updateData['status'] = 'signed';
            $updateData['executed_at'] = date('Y-m-d H:i:s');
            Contract::update((int) $contract['id'], $updateData);
            $success = 'Contract has been fully signed and executed!';
        } else {
            $success = 'Your signature has been recorded successfully!';
        }
        
        // Log contract signed event in workspace activity (best-effort)
        try {
            if (!empty($contract['company_id'])) {
                $currentUser = AuthManager::getCurrentUser();
                $userId = $currentUser['id'] ?? null;
                ActivityLog::log(
                    (int) $contract['company_id'],
                    $userId ? (int) $userId : null,
                    'contract_signed',
                    'contract',
                    (int) $contract['id'],
                    $contract['contract_number'] ?? ($contract['title'] ?? null),
                    null,
                    [
                        'signature_type' => $signatureType,
                        'signer_name' => $signerName,
                        'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
                        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
                    ]
                );
            }
        } catch (Throwable $e) {
            // ignore logging failures
        }
        
        // Refresh contract data
        $contract = Contract::find((int) $contract['id']);
    }
}

// Determine which signature is being captured
$isClientSigning = $contract && $contract['signing_token_client'] === $token;
$isInternalSigning = $contract && $contract['signing_token_internal'] === $token;
$signatureType = $isClientSigning ? 'client' : 'internal';

// Check if already signed using correct field names
$hasSigned = $contract && !empty($contract[$signatureType . '_signed_at']);

// Debug: Show signing status
$debugStatus = [
    'isClientSigning' => $isClientSigning,
    'isInternalSigning' => $isInternalSigning,
    'signatureType' => $signatureType,
    'hasSigned' => $hasSigned,
    'client_signed_at' => $contract['client_signed_at'] ?? null,
    'internal_signed_at' => $contract['internal_signed_at'] ?? null,
];

$workspaceSlug = isset($_GET['workspace']) ? sanitizeText((string) $_GET['workspace']) : null;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode($workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode($workspaceSlug) : '';

$currentTheme = $_GET['theme'] ?? 'light';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

$downloadWorkspaceParam = $workspaceSlug ? '&workspace=' . urlencode($workspaceSlug) : '';
$viewLink = null;
$downloadLink = null;
if ($contract) {
    $timestamp = time();
    $viewLink = "/download.php?action=view&contract_id={$contract['id']}&t={$timestamp}&force=1{$downloadWorkspaceParam}";
    $downloadLink = "/download.php?action=download&contract_id={$contract['id']}&t={$timestamp}{$downloadWorkspaceParam}";
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign Contract · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body class="public-page">
<main class="sign-page">
    <header class="sign-header">
        <div class="sign-header__logo">
            <img src="/assets/KeelanceLogo.png" alt="Keelance logo">
        </div>
        <div class="sign-header__meta">
            <?= h($workspaceCompanyName ? "{$workspaceCompanyName} workspace" : 'Secure Keelance signing portal') ?>
        </div>
    </header>

    <?php if ($error): ?>
        <div class="status-banner error">
            <?= h($error) ?>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="status-banner success">
            <?= h($success) ?>
        </div>
    <?php endif; ?>

    <?php if ($contract && !$hasSigned): ?>
        <section class="card sign-card">
            <div class="sign-card__head">
                <div>
                    <p class="eyebrow"><?= $isClientSigning ? 'Client signature' : 'Internal signature' ?></p>
                    <h1 class="sign-card__title">Review & sign contract</h1>
                    <p class="sign-card__subtitle">
                        Please verify the contract details and provide your legally binding signature below.
                    </p>
                </div>
                <div class="sign-card__actions">
                    <?php if ($viewLink): ?>
                        <a href="<?= h($viewLink) ?>" target="_blank" class="btn-secondary btn-sm">Review contract</a>
                    <?php endif; ?>
                    <?php if ($downloadLink): ?>
                        <a href="<?= h($downloadLink) ?>" class="btn-secondary btn-sm">Download PDF</a>
                    <?php endif; ?>
                </div>
            </div>

            <div class="sign-summary">
                <div class="sign-summary__top">
                    <span class="label-uppercase">Contract</span>
                    <h2><?= h($contract['title'] ?? 'Untitled contract') ?></h2>
                </div>
                <div class="sign-summary__grid">
                    <div class="sign-summary__cell">
                        <span class="label-uppercase">Contract #</span>
                        <p class="sign-summary__value"><?= h($contract['contract_number'] ?? 'CTR-' . $contract['id']) ?></p>
                    </div>
                    <div class="sign-summary__cell">
                        <span class="label-uppercase">Client</span>
                        <p class="sign-summary__value">
                            <?= h($contract['client_name'] ?? 'Unknown') ?>
                            <?php if (!empty($contract['client_company'])): ?>
                                <span class="text-muted"> · <?= h($contract['client_company']) ?></span>
                            <?php endif; ?>
                        </p>
                    </div>
                    <div class="sign-summary__cell">
                        <span class="label-uppercase">Workspace</span>
                        <p class="sign-summary__value">
                            <?= h($workspaceCompanyName ?? 'Keelance workspace') ?>
                        </p>
                    </div>
                </div>
            </div>

            <form method="POST" id="signatureForm" class="sign-form">
                <input type="hidden" name="signature_type" value="<?= h($signatureType) ?>">
                <input type="hidden" name="signature_data" id="signatureData">

                <label class="form-field">
                    <span>Your full name *</span>
                    <input
                        type="text"
                        name="signer_name"
                        class="field-input"
                        required
                        placeholder="Enter your full legal name"
                    >
                </label>

                <div class="sign-section">
                    <div class="sign-section__head">
                        <div>
                            <p class="sign-section__title">Draw your signature *</p>
                            <p class="sign-section__subtitle">Use your mouse or finger to sign inside the box.</p>
                        </div>
                        <div class="sign-section__actions">
                            <button type="button" class="btn-secondary btn-sm" onclick="clearSignature()">Clear</button>
                            <button type="button" class="btn-secondary btn-sm" onclick="drawSignature()">Text signature</button>
                        </div>
                    </div>
                    <div class="signature-pad">
                        <canvas id="signatureCanvas" width="600" height="200"></canvas>
                    </div>
                </div>

                <label class="form-field">
                    <span>Or upload signature image</span>
                    <input type="file" id="signatureUpload" accept="image/*" class="field-input">
                </label>

                <label class="checkbox-field">
                    <input type="checkbox" required>
                    <span>I confirm that I have reviewed this contract and agree to be bound by its terms.</span>
                </label>

                <div class="template-builder-actions">
                    <button type="submit" class="btn-primary">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                            <path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M15.232 5.232l3.536 3.536M9 11l6.232-6.232a2.5 2.5 0 013.536 3.536L9 18H5v-4l4-3z" />
                        </svg>
                        Sign contract
                    </button>
                </div>
            </form>
        </section>
    <?php elseif ($contract && $hasSigned): ?>
        <section class="card sign-card sign-card--success">
            <div class="sign-card__success-icon">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
                    <path stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            </div>
            <div class="sign-card__success-body">
                <h1>Signature recorded</h1>
                <p>Your signature for contract <?= h($contract['contract_number'] ?? 'CTR-' . $contract['id']) ?> has been saved.</p>
                <div class="sign-details">
                    <div>
                        <span class="label-uppercase">Signed on</span>
                        <p><?= date('F j, Y, g:i A', strtotime($contract[$signatureType . '_signed_at'])) ?></p>
                    </div>
                    <div>
                        <span class="label-uppercase">IP address</span>
                        <p><?= h($contract[$signatureType . '_ip']) ?></p>
                    </div>
                </div>
                <?php if ($downloadLink): ?>
                    <div class="sign-card__actions">
                        <a href="<?= h($downloadLink) ?>" class="btn-primary" target="_blank">Download signed copy</a>
                        <?php if (!$isClientSigning): ?>
                            <a href="/contracts.php<?= $workspaceQuery ?>" class="btn-secondary">Back to workspace</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>

    <footer class="sign-footer">
        <p>&copy; 2026 Keelance. All Rights Reserved.</p>
    </footer>
</main>

<script>
const canvas = document.getElementById('signatureCanvas');
const signatureForm = document.getElementById('signatureForm');
const signatureUpload = document.getElementById('signatureUpload');
let ctx = null;
let isDrawing = false;

if (canvas) {
    ctx = canvas.getContext('2d');
    canvas.width = canvas.offsetWidth;
    canvas.height = 200;

    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);

    canvas.addEventListener('touchstart', handleTouch, { passive: false });
    canvas.addEventListener('touchmove', handleTouch, { passive: false });
    canvas.addEventListener('touchend', stopDrawing);
}

function startDrawing(e) {
    if (!ctx) return;
    isDrawing = true;
    const rect = canvas.getBoundingClientRect();
    ctx.beginPath();
    ctx.moveTo((e.clientX ?? e.touches[0].clientX) - rect.left, (e.clientY ?? e.touches[0].clientY) - rect.top);
}

function draw(e) {
    if (!isDrawing || !ctx) return;
    const rect = canvas.getBoundingClientRect();
    const clientX = e.clientX ?? (e.touches ? e.touches[0].clientX : null);
    const clientY = e.clientY ?? (e.touches ? e.touches[0].clientY : null);
    if (clientX === null || clientY === null) return;
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.strokeStyle = '#000';
    ctx.lineTo(clientX - rect.left, clientY - rect.top);
    ctx.stroke();
}

function stopDrawing() {
    if (!ctx) return;
    isDrawing = false;
    saveSignature();
}

function handleTouch(e) {
    e.preventDefault();
    if (e.type === 'touchstart') {
        startDrawing(e);
    } else if (e.type === 'touchmove') {
        draw(e);
    }
}

function clearSignature() {
    if (!ctx) return;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    const field = document.getElementById('signatureData');
    if (field) field.value = '';
}

function saveSignature() {
    if (!ctx) return;
    const signatureData = canvas.toDataURL();
    const field = document.getElementById('signatureData');
    if (field) field.value = signatureData;
}

function drawSignature() {
    if (!ctx) return;
    const name = prompt('Enter your name for signature:');
    if (name) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.font = '30px "Kalam", "Segoe Script", cursive';
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(name, canvas.width / 2, canvas.height / 2);
        saveSignature();
    }
}

if (signatureUpload && ctx) {
    signatureUpload.addEventListener('change', function(e) {
        const file = e.target.files?.[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function(event) {
            const img = new Image();
            img.onload = function() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                const scale = Math.min(canvas.width / img.width, canvas.height / img.height);
                const width = img.width * scale;
                const height = img.height * scale;
                const x = (canvas.width - width) / 2;
                const y = (canvas.height - height) / 2;
                ctx.drawImage(img, x, y, width, height);
                saveSignature();
            };
            img.src = event.target?.result;
        };
        reader.readAsDataURL(file);
    });
}

if (signatureForm) {
    signatureForm.addEventListener('submit', function(e) {
        const signatureData = document.getElementById('signatureData')?.value;
        if (!signatureData) {
            e.preventDefault();
            alert('Please provide your signature before submitting.');
        }
    });
}
</script>

</body>
</html>
