<?php
/**
 * LandSecure Digital Land Certificate
 * Generates a professional, verifiable land certificate
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

// Initialize session
initSecureSession();

// Check authentication
if(!isset($_SESSION['user_id'])) {
    header('Location: ' . url('login'));
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';
$land_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if($land_id <= 0) {
    header('Location: ' . url('lands'));
    exit;
}

// Get land details with owner info
$land_sql = "SELECT l.*, u.full_name as owner_name, u.phone as owner_phone, u.email as owner_email,
             u.username as owner_username, u.user_type,
             r.name as region_name, d.name as district_name
             FROM lands l
             JOIN users u ON l.user_id = u.id
             LEFT JOIN regions r ON l.region_id = r.id
             LEFT JOIN districts d ON l.district_id = d.id
             WHERE l.id = $land_id";

// Check access rights
if($user_role == 'admin') {
    // Admin can view all
} elseif($user_role == 'broker') {
    $land_sql .= " AND (l.user_id = $user_id OR l.user_id IN (SELECT id FROM users WHERE referred_by_broker = $user_id))";
} else {
    $land_sql .= " AND l.user_id = $user_id";
}

$land_result = mysqli_query($conn, $land_sql);
if(mysqli_num_rows($land_result) == 0) {
    header('Location: ' . url('lands?error=Land not found or access denied'));
    exit;
}

$land = mysqli_fetch_assoc($land_result);

// Get beacon points
$points_sql = "SELECT * FROM beacon_points WHERE land_id = $land_id ORDER BY point_order";
$points_result = mysqli_query($conn, $points_sql);
$beacon_points = [];
while($point = mysqli_fetch_assoc($points_result)) {
    $beacon_points[] = $point;
}

// Get landmarks
$landmarks_sql = "SELECT * FROM beacon_landmarks WHERE land_id = $land_id ORDER BY from_point";
$landmarks_result = mysqli_query($conn, $landmarks_sql);
$landmarks = [];
while($lm = mysqli_fetch_assoc($landmarks_result)) {
    $landmarks[] = $lm;
}

// Generate certificate ID if not exists
$certificate_id = 'LS-' . date('Y', strtotime($land['created_at'])) . '-' . str_pad($land['id'], 6, '0', STR_PAD_LEFT);

// Calculate land center for map
$center_lat = 0;
$center_lng = 0;
if(count($beacon_points) > 0) {
    foreach($beacon_points as $point) {
        $center_lat += $point['latitude'];
        $center_lng += $point['longitude'];
    }
    $center_lat /= count($beacon_points);
    $center_lng /= count($beacon_points);
}

// Generate verification hash
$verification_hash = substr(md5($certificate_id . $land['created_at'] . $land['user_id']), 0, 12);
$verification_url = APP_URL . '/verify?code=' . $certificate_id . '-' . strtoupper($verification_hash);

// Determine verification status
$verification_status = 'User Registered';
$verification_class = 'status-registered';
if($land['is_verified'] ?? false) {
    $verification_status = 'Surveyor Verified';
    $verification_class = 'status-verified';
}

$issue_date = date('d F Y', strtotime($land['created_at']));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Land Certificate - <?php echo $certificate_id; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f1f5f9;
            min-height: 100vh;
        }

        .certificate-actions {
            max-width: 900px;
            margin: 20px auto;
            padding: 0 20px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 12px 24px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
        }

        .btn-back {
            background: white;
            color: #64748b;
            border: 1px solid #e2e8f0;
        }

        .btn-back:hover {
            background: #f8fafc;
        }

        .btn-print {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-print:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }

        .btn-download {
            background: linear-gradient(135deg, #22c55e, #16a34a);
            color: white;
        }

        .btn-download:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(34, 197, 94, 0.4);
        }

        .certificate-container {
            max-width: 900px;
            margin: 0 auto 40px;
            padding: 0 20px;
        }

        .certificate {
            background: white;
            border-radius: 0;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            position: relative;
        }

        /* Certificate Border Design */
        .certificate::before {
            content: '';
            position: absolute;
            top: 10px;
            left: 10px;
            right: 10px;
            bottom: 10px;
            border: 3px solid #1a3a6e;
            pointer-events: none;
            z-index: 1;
        }

        .certificate::after {
            content: '';
            position: absolute;
            top: 15px;
            left: 15px;
            right: 15px;
            bottom: 15px;
            border: 1px solid #d4af37;
            pointer-events: none;
            z-index: 1;
        }

        /* Header */
        .certificate-header {
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%);
            color: white;
            padding: 40px;
            text-align: center;
            position: relative;
        }

        .certificate-header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 8px;
            background: linear-gradient(90deg, #d4af37, #f5d77a, #d4af37);
        }

        .logo-section {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-bottom: 20px;
        }

        .logo-icon {
            width: 70px;
            height: 70px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 3px solid #d4af37;
        }

        .logo-icon i {
            font-size: 32px;
            color: #d4af37;
        }

        .certificate-title {
            font-family: 'Playfair Display', serif;
            font-size: 32px;
            font-weight: 700;
            letter-spacing: 3px;
            text-transform: uppercase;
            margin-bottom: 5px;
        }

        .certificate-subtitle {
            font-size: 16px;
            opacity: 0.9;
            letter-spacing: 2px;
        }

        .certificate-id-badge {
            display: inline-block;
            background: rgba(255, 255, 255, 0.2);
            padding: 10px 25px;
            border-radius: 30px;
            margin-top: 20px;
            font-size: 14px;
            letter-spacing: 1px;
        }

        /* Body */
        .certificate-body {
            padding: 40px;
        }

        /* Certificate Meta */
        .certificate-meta {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 30px;
            padding-bottom: 30px;
            border-bottom: 2px solid #f1f5f9;
        }

        .meta-item {
            text-align: center;
        }

        .meta-label {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #64748b;
            margin-bottom: 5px;
        }

        .meta-value {
            font-size: 15px;
            font-weight: 600;
            color: #1e293b;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
        }

        .status-registered {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
        }

        .status-verified {
            background: rgba(34, 197, 94, 0.1);
            color: #22c55e;
        }

        /* Sections */
        .section {
            margin-bottom: 30px;
        }

        .section-title {
            font-family: 'Playfair Display', serif;
            font-size: 18px;
            font-weight: 600;
            color: #1a3a6e;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #d4af37;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-title i {
            color: #d4af37;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }

        .info-item {
            background: #f8fafc;
            padding: 15px;
            border-radius: 10px;
            border-left: 3px solid #1a3a6e;
        }

        .info-item.full-width {
            grid-column: span 2;
        }

        .info-label {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #64748b;
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
        }

        /* Map */
        .map-container {
            height: 300px;
            border-radius: 12px;
            overflow: hidden;
            border: 2px solid #e2e8f0;
            margin-bottom: 20px;
        }

        #certificateMap {
            height: 100%;
            width: 100%;
        }

        /* Coordinates Table */
        .coordinates-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        .coordinates-table th {
            background: #1a3a6e;
            color: white;
            padding: 12px;
            text-align: left;
            font-weight: 600;
        }

        .coordinates-table td {
            padding: 10px 12px;
            border-bottom: 1px solid #e2e8f0;
        }

        .coordinates-table tr:nth-child(even) {
            background: #f8fafc;
        }

        .coordinates-table tr:hover {
            background: #f1f5f9;
        }

        /* QR Section */
        .qr-section {
            display: flex;
            align-items: center;
            gap: 30px;
            background: linear-gradient(135deg, #f8fafc, #e2e8f0);
            padding: 25px;
            border-radius: 12px;
            margin-top: 30px;
        }

        .qr-code {
            width: 140px;
            height: 140px;
            background: white;
            padding: 10px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .qr-code img {
            width: 100%;
            height: 100%;
        }

        .qr-info {
            flex: 1;
        }

        .qr-info h4 {
            font-family: 'Playfair Display', serif;
            font-size: 18px;
            color: #1a3a6e;
            margin-bottom: 10px;
        }

        .qr-info p {
            color: #64748b;
            font-size: 14px;
            margin-bottom: 10px;
        }

        .verification-url {
            font-family: monospace;
            font-size: 12px;
            background: white;
            padding: 10px 15px;
            border-radius: 8px;
            color: #1a3a6e;
            word-break: break-all;
        }

        /* Seal */
        .certificate-seal {
            position: absolute;
            bottom: 80px;
            right: 60px;
            width: 120px;
            height: 120px;
            opacity: 0.15;
        }

        .certificate-seal-inner {
            width: 100%;
            height: 100%;
            border: 4px solid #1a3a6e;
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            transform: rotate(-15deg);
        }

        .certificate-seal-inner i {
            font-size: 36px;
            color: #1a3a6e;
            margin-bottom: 5px;
        }

        .certificate-seal-inner span {
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #1a3a6e;
        }

        /* Footer */
        .certificate-footer {
            background: #f8fafc;
            padding: 25px 40px;
            border-top: 1px solid #e2e8f0;
        }

        .disclaimer {
            font-size: 11px;
            color: #64748b;
            text-align: center;
            line-height: 1.6;
            font-style: italic;
        }

        .footer-seal {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e2e8f0;
        }

        .footer-seal i {
            color: #d4af37;
            font-size: 24px;
        }

        .footer-seal span {
            font-size: 12px;
            font-weight: 600;
            color: #1a3a6e;
            letter-spacing: 2px;
            text-transform: uppercase;
        }

        /* Premium Badge */
        .premium-indicator {
            position: absolute;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 6px;
            z-index: 10;
        }

        /* Print Styles - Force colors to print */
        @media print {
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }

            body {
                background: white !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }

            .certificate-actions {
                display: none !important;
            }

            .certificate-container {
                margin: 0;
                padding: 0;
                max-width: none;
            }

            .certificate {
                box-shadow: none;
                border: 2px solid #1a3a6e !important;
            }

            .certificate::before {
                border: 3px solid #1a3a6e !important;
            }

            .certificate::after {
                border: 1px solid #d4af37 !important;
            }

            /* Header with colors */
            .certificate-header {
                background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%) !important;
                color: white !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }

            .certificate-header::after {
                background: linear-gradient(90deg, #d4af37, #f5d77a, #d4af37) !important;
            }

            .logo-icon {
                background: rgba(255, 255, 255, 0.15) !important;
                border: 3px solid #d4af37 !important;
            }

            .logo-icon i {
                color: #d4af37 !important;
            }

            .certificate-id-badge {
                background: rgba(255, 255, 255, 0.2) !important;
            }

            /* Certificate Meta - Keep 3 columns on one line */
            .certificate-meta {
                display: grid !important;
                grid-template-columns: repeat(3, 1fr) !important;
                gap: 15px !important;
            }

            .meta-item {
                text-align: center !important;
            }

            /* Info Grid - Keep 2 columns side by side */
            .info-grid {
                display: grid !important;
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 12px !important;
            }

            .info-item.full-width {
                grid-column: span 2 !important;
            }

            /* Section titles */
            .section-title {
                color: #1a3a6e !important;
                border-bottom: 2px solid #d4af37 !important;
            }

            .section-title i {
                color: #d4af37 !important;
            }

            /* Info items */
            .info-item {
                background: #f8fafc !important;
                border-left: 3px solid #1a3a6e !important;
                padding: 12px !important;
            }

            /* Status badges */
            .status-registered {
                background: rgba(59, 130, 246, 0.1) !important;
                color: #3b82f6 !important;
            }

            .status-verified {
                background: rgba(34, 197, 94, 0.1) !important;
                color: #22c55e !important;
            }

            /* Table */
            .coordinates-table {
                width: 100% !important;
            }

            .coordinates-table th {
                background: #1a3a6e !important;
                color: white !important;
            }

            .coordinates-table tr:nth-child(even) {
                background: #f8fafc !important;
            }

            /* QR Section - Keep side by side */
            .qr-section {
                display: flex !important;
                flex-direction: row !important;
                align-items: center !important;
                gap: 25px !important;
                background: linear-gradient(135deg, #f8fafc, #e2e8f0) !important;
            }

            .qr-code {
                width: 120px !important;
                min-width: 120px !important;
                height: 120px !important;
            }

            .qr-info {
                flex: 1 !important;
                text-align: left !important;
            }

            .qr-info h4 {
                color: #1a3a6e !important;
            }

            .verification-url {
                background: white !important;
                color: #1a3a6e !important;
                font-size: 11px !important;
            }

            /* Footer */
            .certificate-footer {
                background: #f8fafc !important;
            }

            .footer-seal i {
                color: #d4af37 !important;
            }

            .footer-seal span {
                color: #1a3a6e !important;
            }

            /* Premium indicator */
            .premium-indicator {
                background: linear-gradient(135deg, #f59e0b, #d97706) !important;
                color: white !important;
            }

            /* Seal */
            .certificate-seal-inner {
                border: 4px solid #1a3a6e !important;
            }

            .certificate-seal-inner i,
            .certificate-seal-inner span {
                color: #1a3a6e !important;
            }

            .map-container {
                height: 250px;
            }

            .btn, .certificate-actions {
                display: none !important;
            }

            /* Page break control */
            .section {
                page-break-inside: avoid;
            }

            .certificate-body {
                padding: 30px !important;
            }
        }

        @media (max-width: 768px) {
            .certificate-meta {
                grid-template-columns: 1fr;
            }

            .info-grid {
                grid-template-columns: 1fr;
            }

            .info-item.full-width {
                grid-column: span 1;
            }

            .qr-section {
                flex-direction: column;
                text-align: center;
            }

            .certificate-header {
                padding: 30px 20px;
            }

            .certificate-title {
                font-size: 24px;
            }

            .certificate-body {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="certificate-actions">
        <a href="<?php echo url('lands'); ?>" class="btn btn-back">
            <i class="fas fa-arrow-left"></i> Back to Lands
        </a>
        <button class="btn btn-print" onclick="window.print()">
            <i class="fas fa-print"></i> Print Certificate
        </button>
        <button class="btn btn-download" onclick="downloadAsPDF()">
            <i class="fas fa-download"></i> Download PDF
        </button>
    </div>

    <div class="certificate-container">
        <div class="certificate">
            <?php if($land['user_type'] == 'premium'): ?>
            <div class="premium-indicator">
                <i class="fas fa-crown"></i> Premium Account
            </div>
            <?php endif; ?>

            <!-- Header -->
            <div class="certificate-header">
                <div class="logo-section">
                    <div class="logo-icon">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                </div>
                <h1 class="certificate-title">LandSecure</h1>
                <p class="certificate-subtitle">Digital Land Certificate</p>
                <div class="certificate-id-badge">
                    <i class="fas fa-certificate"></i>
                    Certificate ID: <?php echo $certificate_id; ?>
                </div>
            </div>

            <!-- Body -->
            <div class="certificate-body">
                <!-- Certificate Meta -->
                <div class="certificate-meta">
                    <div class="meta-item">
                        <div class="meta-label">Certificate ID</div>
                        <div class="meta-value"><?php echo $certificate_id; ?></div>
                    </div>
                    <div class="meta-item">
                        <div class="meta-label">Issue Date</div>
                        <div class="meta-value"><?php echo $issue_date; ?></div>
                    </div>
                    <div class="meta-item">
                        <div class="meta-label">Verification Status</div>
                        <div class="meta-value">
                            <span class="status-badge <?php echo $verification_class; ?>">
                                <i class="fas fa-check-circle"></i>
                                <?php echo $verification_status; ?>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Owner Information -->
                <div class="section">
                    <h3 class="section-title">
                        <i class="fas fa-user"></i>
                        Owner Information
                    </h3>
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">Owner Full Name</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['owner_name']); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Phone Number</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['owner_phone'] ?: 'Not provided'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Email Address</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['owner_email'] ?: 'Not provided'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Account ID</div>
                            <div class="info-value">LS-<?php echo str_pad($land['user_id'], 5, '0', STR_PAD_LEFT); ?></div>
                        </div>
                    </div>
                </div>

                <!-- Land Information -->
                <div class="section">
                    <h3 class="section-title">
                        <i class="fas fa-map-marked-alt"></i>
                        Land Information
                    </h3>
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">Land ID</div>
                            <div class="info-value">LS-LAND-<?php echo str_pad($land['id'], 5, '0', STR_PAD_LEFT); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Land Name</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['land_name']); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Region</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['region_name'] ?: 'Not specified'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">District</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['district_name'] ?: 'Not specified'); ?></div>
                        </div>
                        <div class="info-item full-width">
                            <div class="info-label">Description</div>
                            <div class="info-value"><?php echo htmlspecialchars($land['description'] ?: 'No description provided'); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Registration Date</div>
                            <div class="info-value"><?php echo date('d F Y', strtotime($land['created_at'])); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Total Beacon Points</div>
                            <div class="info-value"><?php echo count($beacon_points); ?> Points</div>
                        </div>
                    </div>
                </div>

                <!-- GPS Location & Map -->
                <div class="section">
                    <h3 class="section-title">
                        <i class="fas fa-map"></i>
                        GPS Location & Boundary
                    </h3>
                    <div class="info-grid" style="margin-bottom: 20px;">
                        <div class="info-item">
                            <div class="info-label">Center Latitude</div>
                            <div class="info-value"><?php echo number_format($center_lat, 6); ?></div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">Center Longitude</div>
                            <div class="info-value"><?php echo number_format($center_lng, 6); ?></div>
                        </div>
                    </div>

                    <div class="map-container">
                        <div id="certificateMap"></div>
                    </div>
                </div>

                <!-- Boundary Coordinates -->
                <?php if(count($beacon_points) > 0): ?>
                <div class="section">
                    <h3 class="section-title">
                        <i class="fas fa-draw-polygon"></i>
                        Boundary Coordinates
                    </h3>
                    <table class="coordinates-table">
                        <thead>
                            <tr>
                                <th>Point</th>
                                <th>Label</th>
                                <th>Latitude</th>
                                <th>Longitude</th>
                                <th>GPS Accuracy</th>
                                <?php if(!empty($beacon_points[0]['beacon_number'])): ?>
                                <th>Beacon Number</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($beacon_points as $index => $point): ?>
                            <tr>
                                <td><strong>Point <?php echo chr(65 + $index); ?></strong></td>
                                <td><?php echo htmlspecialchars($point['point_label'] ?: '-'); ?></td>
                                <td><?php echo number_format($point['latitude'], 6); ?></td>
                                <td><?php echo number_format($point['longitude'], 6); ?></td>
                                <td><?php echo isset($point['accuracy']) && $point['accuracy'] > 0 ? number_format($point['accuracy'], 1) . ' m' : '-'; ?></td>
                                <?php if(!empty($beacon_points[0]['beacon_number'])): ?>
                                <td><?php echo htmlspecialchars($point['beacon_number'] ?: '-'); ?></td>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <!-- Landmarks -->
                <?php if(count($landmarks) > 0): ?>
                <div class="section">
                    <h3 class="section-title">
                        <i class="fas fa-road"></i>
                        Boundary Landmarks
                    </h3>
                    <table class="coordinates-table">
                        <thead>
                            <tr>
                                <th>From Point</th>
                                <th>To Point</th>
                                <th>Landmark Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($landmarks as $lm): ?>
                            <tr>
                                <td>Point <?php echo chr(64 + $lm['from_point']); ?></td>
                                <td>Point <?php echo chr(64 + $lm['to_point']); ?></td>
                                <td><?php echo htmlspecialchars($lm['landmark_description']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <!-- QR Verification -->
                <div class="qr-section">
                    <div class="qr-code">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=<?php echo urlencode($verification_url); ?>" alt="QR Code">
                    </div>
                    <div class="qr-info">
                        <h4><i class="fas fa-qrcode"></i> Scan to Verify</h4>
                        <p>Scan this QR code or visit the URL below to verify the authenticity of this certificate.</p>
                        <div class="verification-url"><?php echo $verification_url; ?></div>
                    </div>
                </div>

                <!-- Seal Watermark -->
                <div class="certificate-seal">
                    <div class="certificate-seal-inner">
                        <i class="fas fa-check-circle"></i>
                        <span>Verified</span>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div class="certificate-footer">
                <p class="disclaimer">
                    This certificate confirms a digital land record within the LandSecure platform. It serves as documentation of land registration
                    and boundary coordinates as provided by the registered owner. This certificate does not replace official government land title
                    documents or certificates of occupancy. For legal land ownership verification, please consult the relevant government land registry.
                </p>
                <div class="footer-seal">
                    <i class="fas fa-shield-alt"></i>
                    <span>Verified by LandSecure Digital Registry</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Initialize map
        document.addEventListener('DOMContentLoaded', function() {
            const points = <?php echo json_encode(array_map(function($p) {
                return [$p['latitude'], $p['longitude'], $p['point_label']];
            }, $beacon_points)); ?>;

            if(points.length > 0) {
                const map = L.map('certificateMap', {
                    zoomControl: true,
                    scrollWheelZoom: false
                });

                L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                    attribution: '&copy; Esri'
                }).addTo(map);

                // Create polygon
                const polygonCoords = points.map(p => [p[0], p[1]]);
                const polygon = L.polygon(polygonCoords, {
                    color: '#d4af37',
                    weight: 3,
                    fillColor: '#1a3a6e',
                    fillOpacity: 0.3
                }).addTo(map);

                // Add markers for each point
                points.forEach((point, index) => {
                    const letter = String.fromCharCode(65 + index);
                    const marker = L.marker([point[0], point[1]], {
                        icon: L.divIcon({
                            className: 'custom-marker',
                            html: `<div style="width:28px;height:28px;background:#1a3a6e;color:white;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:12px;border:2px solid #d4af37;">${letter}</div>`,
                            iconSize: [28, 28],
                            iconAnchor: [14, 14]
                        })
                    }).addTo(map);
                });

                // Fit bounds
                map.fitBounds(polygon.getBounds(), { padding: [30, 30] });
            } else {
                document.getElementById('certificateMap').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#64748b;">No boundary points defined</div>';
            }
        });

        function downloadAsPDF() {
            alert('To save as PDF, use the Print function (Ctrl+P) and select "Save as PDF" as the printer.');
            window.print();
        }
    </script>
</body>
</html>
