<?php
require_once('config.php');
require_once('Document.php');
require_once('PDFGenerator.php');
require_once('EmailHandler.php');

// Check if user is logged in (optional - can be modified for customer-facing)
$user_id = $_SESSION['user_id'] ?? null;
$document_id = isset($_GET['id']) ? intval($_GET['id']) : null;

// If document ID provided, load existing document
if ($document_id) {
    $doc = new Document($pdo);
    $document = $doc->get($document_id);

    if (!$document) {
        die('Document not found');
    }
} else {
    $document = null;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        die('CSRF token validation failed');
    }

    $doc = new Document($pdo);

    // Create new document if not editing
    if (!$document_id) {
        $customer_data = [
            'customer_name' => sanitize_input($_POST['customer_name'] ?? ''),
            'customer_email' => filter_var($_POST['customer_email'] ?? '', FILTER_SANITIZE_EMAIL),
            'customer_phone' => sanitize_input($_POST['customer_phone'] ?? ''),
            'vehicle_year' => sanitize_input($_POST['vehicle_year'] ?? ''),
            'vehicle_make' => sanitize_input($_POST['vehicle_make'] ?? ''),
            'vehicle_model' => sanitize_input($_POST['vehicle_model'] ?? '')
        ];

        // Collect all document fields
        $document_fields = $customer_data;
        foreach ($_POST as $key => $value) {
            if (!in_array($key, ['customer_name', 'customer_email', 'customer_phone', 'vehicle_year', 'vehicle_make', 'vehicle_model', 'csrf_token', 'signature_customer', 'signature_admin', 'document_type'])) {
                $document_fields[$key] = sanitize_input($value);
            }
        }

        $result = $doc->create(
            $user_id,
            isset($_POST['template_id']) ? intval($_POST['template_id']) : null,
            sanitize_input($_POST['document_type'] ?? 'warranty'),
            $customer_data,
            $document_fields
        );

        if ($result['success']) {
            $document_id = $result['document_id'];
            $document = $doc->get($document_id, $user_id);
            $success_message = 'Document created successfully. Now add signatures below.';
        } else {
            $error_message = 'Error creating document: ' . $result['error'];
        }
    }
}

// Handle signature submission
if (isset($_POST['add_signature']) && $document_id) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        die('CSRF token validation failed');
    }

    $doc = new Document($pdo);
    $signature_data = $_POST['signature_data'] ?? '';
    $signer_name = sanitize_input($_POST['signer_name'] ?? '');
    $signer_email = filter_var($_POST['signer_email'] ?? '', FILTER_SANITIZE_EMAIL);
    $signer_role = in_array($_POST['signer_role'] ?? 'customer', ['customer', 'admin', 'witness']) ? $_POST['signer_role'] : 'customer';

    if ($signature_data && $signer_name) {
        $result = $doc->addSignature($document_id, $signature_data, $signer_name, $signer_email, $signer_role);

        if ($result) {
            // Generate PDF
            $pdf_gen = new PDFGenerator($pdo);
            $pdf_result = $pdf_gen->generateFromDocument($document_id, true);

            if ($pdf_result['success']) {
                // Save PDF path
                $doc->savePdfPath($document_id, $pdf_result['filepath']);

                // Send emails
                $email_handler = new EmailHandler($pdo);
                $email_result = $email_handler->sendSignedDocument($document_id, $pdf_result['filepath']);

                $success_message = 'Signature added successfully! Document has been generated and emails sent.';

                // Reload document
                $document = $doc->get($document_id, $user_id);
            } else {
                $error_message = 'Error generating PDF: ' . $pdf_result['error'];
            }
        } else {
            $error_message = 'Error adding signature';
        }
    } else {
        $error_message = 'Please draw a signature and enter signer name';
    }
}

$csrf_token = set_csrf_token();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Signing System</title>
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 900px; margin: 0 auto; }
        .header {
            background: white;
            padding: 30px;
            border-radius: 10px 10px 0 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header h1 { color: #333; margin-bottom: 10px; }
        .header p { color: #666; }
        .content {
            background: white;
            padding: 30px;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            font-family: inherit;
        }
        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .form-row.full { grid-template-columns: 1fr; }
        .signature-pad-container {
            border: 2px solid #ddd;
            border-radius: 5px;
            margin-bottom: 10px;
            background: #f9f9f9;
        }
        .signature-canvas {
            width: 100%;
            height: 200px;
            display: block;
            border-radius: 5px;
        }
        .signature-controls {
            display: flex;
            gap: 10px;
            padding: 10px;
            background: #f0f0f0;
            border-radius: 0 0 5px 5px;
        }
        button {
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .btn-primary {
            background: #667eea;
            color: white;
        }
        .btn-primary:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .btn-secondary {
            background: #e0e0e0;
            color: #333;
        }
        .btn-secondary:hover {
            background: #d0d0d0;
        }
        .btn-danger {
            background: #f56565;
            color: white;
        }
        .btn-success {
            background: #48bb78;
            color: white;
        }
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .alert-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .document-info {
            background: #f0f7ff;
            border-left: 4px solid #667eea;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .signature-list {
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-top: 20px;
        }
        .signature-item {
            background: white;
            padding: 12px;
            margin-bottom: 10px;
            border-left: 4px solid #48bb78;
            border-radius: 3px;
        }
        .signature-item strong { color: #333; }
        .signature-item small { color: #999; display: block; margin-top: 5px; }
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        .tab-btn {
            padding: 12px 20px;
            background: none;
            border: none;
            border-bottom: 3px solid transparent;
            cursor: pointer;
            font-weight: 600;
            color: #999;
        }
        .tab-btn.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        @media (max-width: 768px) {
            .form-row { grid-template-columns: 1fr; }
            .signature-canvas { height: 150px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📋 Legal Document Signing System</h1>
            <p>Create, sign, and manage contracts, warranties, and service agreements with legal signatures</p>
        </div>

        <div class="content">
            <?php if (isset($success_message)): ?>
                <div class="alert alert-success"><?php echo $success_message; ?></div>
            <?php endif; ?>

            <?php if (isset($error_message)): ?>
                <div class="alert alert-error"><?php echo $error_message; ?></div>
            <?php endif; ?>

            <?php if ($document): ?>
                <!-- Document Info -->
                <div class="document-info">
                    <strong>Document ID:</strong> <?php echo htmlspecialchars($document['document_hash']); ?><br>
                    <strong>Type:</strong> <?php echo ucfirst(str_replace('_', ' ', $document['document_type'])); ?><br>
                    <strong>Customer:</strong> <?php echo htmlspecialchars($document['customer_name']); ?><br>
                    <strong>Status:</strong> <span style="color: <?php echo $document['status'] === 'signed' ? 'green' : 'orange'; ?>;"><?php echo ucfirst($document['status']); ?></span>
                </div>

                <!-- Tabs -->
                <div class="tabs">
                    <button class="tab-btn active" onclick="switchTab('preview')">📄 Preview</button>
                    <button class="tab-btn" onclick="switchTab('signature')">✍️ Sign Document</button>
                    <button class="tab-btn" onclick="switchTab('history')">📋 Signatures</button>
                </div>

                <!-- Preview Tab -->
                <div id="preview" class="tab-content active">
                    <h3>Document Details</h3>
                    <div style="background: #f9f9f9; padding: 15px; border-radius: 5px; margin-top: 15px;">
                        <?php foreach ($document['document_data'] as $key => $value): ?>
                            <div style="margin-bottom: 12px;">
                                <strong><?php echo ucwords(str_replace('_', ' ', $key)); ?>:</strong><br>
                                <?php echo htmlspecialchars(is_array($value) ? json_encode($value) : $value); ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Signature Tab -->
                <div id="signature" class="tab-content">
                    <?php if ($document['status'] !== 'signed'): ?>
                        <h3>Add Signature</h3>
                        <form method="POST" style="margin-top: 15px;">
                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                            <input type="hidden" name="add_signature" value="1">
                            <input type="hidden" name="signature_data" id="signature_data">

                            <div class="form-row">
                                <div class="form-group">
                                    <label>Signer Name *</label>
                                    <input type="text" name="signer_name" required>
                                </div>
                                <div class="form-group">
                                    <label>Signer Email</label>
                                    <input type="email" name="signer_email">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Role *</label>
                                <select name="signer_role" required>
                                    <option value="customer">Customer</option>
                                    <option value="admin">Admin/Witness</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label>Sign Here (Use Touch or Mouse) *</label>
                                <div class="signature-pad-container">
                                    <canvas class="signature-canvas" id="signature_canvas"></canvas>
                                    <div class="signature-controls">
                                        <button type="button" class="btn-secondary" id="clear_signature">Clear Signature</button>
                                        <span style="flex: 1; text-align: center; color: #999;">Draw your signature above</span>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="btn-primary btn-lg">✓ Sign & Finalize Document</button>
                        </form>
                    <?php else: ?>
                        <div class="alert alert-success">✓ This document has been successfully signed and completed.</div>
                    <?php endif; ?>
                </div>

                <!-- History Tab -->
                <div id="history" class="tab-content">
                    <h3>Signature History</h3>
                    <?php if (!empty($document['signatures'])): ?>
                        <div class="signature-list">
                            <?php foreach ($document['signatures'] as $sig): ?>
                                <div class="signature-item">
                                    <strong><?php echo htmlspecialchars($sig['signer_name']); ?></strong> (<?php echo $sig['signer_role']; ?>)
                                    <small>Signed: <?php echo $sig['signature_timestamp']; ?></small>
                                    <?php if ($sig['signer_email']): ?>
                                        <small>Email: <?php echo htmlspecialchars($sig['signer_email']); ?></small>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p>No signatures yet. Add a signature above.</p>
                    <?php endif; ?>
                </div>

            <?php else: ?>
                <!-- Create New Document Form -->
                <h2>Create New Document</h2>
                <form method="POST" style="margin-top: 20px;">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">

                    <h3 style="margin-top: 25px; margin-bottom: 15px;">Customer Information</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Customer Name *</label>
                            <input type="text" name="customer_name" required>
                        </div>
                        <div class="form-group">
                            <label>Email *</label>
                            <input type="email" name="customer_email" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="tel" name="customer_phone">
                        </div>
                        <div class="form-group">
                            <label>Document Type *</label>
                            <select name="document_type" required>
                                <option value="warranty">Warranty Agreement</option>
                                <option value="service_agreement">Service Agreement</option>
                                <option value="finance_agreement">Finance Agreement</option>
                                <option value="purchase_agreement">Purchase Agreement</option>
                                <option value="contract">General Contract</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>

                    <h3 style="margin-top: 25px; margin-bottom: 15px;">Vehicle Information</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Year</label>
                            <input type="text" name="vehicle_year">
                        </div>
                        <div class="form-group">
                            <label>Make</label>
                            <input type="text" name="vehicle_make">
                        </div>
                        <div class="form-group">
                            <label>Model</label>
                            <input type="text" name="vehicle_model">
                        </div>
                    </div>

                    <h3 style="margin-top: 25px; margin-bottom: 15px;">Agreement Details</h3>
                    <div class="form-group form-row full">
                        <label>Agreement Terms & Conditions *</label>
                        <textarea name="agreement_terms" required placeholder="Enter the full terms and conditions..."></textarea>
                    </div>

                    <div class="form-group form-row full">
                        <label>Price/Amount</label>
                        <input type="text" name="amount">
                    </div>

                    <div class="form-group form-row full">
                        <label>Additional Notes</label>
                        <textarea name="notes" placeholder="Any additional information..."></textarea>
                    </div>

                    <button type="submit" class="btn-primary" style="width: 100%; padding: 15px;">Create Document</button>
                </form>
            <?php endif; ?>

        </div>
    </div>

    <script>
        // Signature Pad initialization
        const canvas = document.getElementById('signature_canvas');
        let signaturePad = null;

        if (canvas) {
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;

            signaturePad = new SignaturePad(canvas, {
                backgroundColor: 'rgba(255,255,255,0)',
                penColor: '#000000',
                velocityFilterWeight: 0.7,
                minWidth: 0.5,
                maxWidth: 2.5,
                throttle: 16
            });

            // Clear signature button
            document.getElementById('clear_signature')?.addEventListener('click', function() {
                signaturePad.clear();
            });

            // Form submission - save signature data
            document.querySelector('form')?.addEventListener('submit', function(e) {
                if (document.getElementById('signature_data')) {
                    if (signaturePad.isEmpty()) {
                        alert('Please provide a signature');
                        e.preventDefault();
                        return;
                    }
                    document.getElementById('signature_data').value = signaturePad.toDataURL();
                }
            });
        }

        // Tab switching
        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });

            // Remove active class from all buttons
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            // Show selected tab
            document.getElementById(tabName).classList.add('active');

            // Mark button as active
            event.target.classList.add('active');

            // Redraw signature pad if switching to signature tab
            if (tabName === 'signature' && signaturePad) {
                setTimeout(() => {
                    canvas.width = canvas.offsetWidth;
                    canvas.height = canvas.offsetHeight;
                    signaturePad.resizeCanvas();
                }, 100);
            }
        }

        // Make signature pad responsive
        window.addEventListener('resize', function() {
            if (signaturePad && canvas.offsetParent !== null) {
                canvas.width = canvas.offsetWidth;
                canvas.height = canvas.offsetHeight;
                signaturePad.resizeCanvas();
            }
        });
    </script>
</body>
</html>
