<?php
/**
 * CBC Digital Land Certificate Generator
 * Generates and displays verified digital land certificates with QR codes
 * Part of the Community Boundary Confirmation system
 */

session_start();
require_once 'db_connect.php';

$land_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$qr_code = isset($_GET['qr']) ? mysqli_real_escape_string($conn, $_GET['qr']) : '';

// Get certificate by land_id or QR code
$certificate = null;
$land = null;

if($land_id) {
    // Get by land ID - check if certificate exists in land_certificates table
    $result = mysqli_query($conn, "
        SELECT lc.*, l.id as land_id
        FROM land_certificates lc
        JOIN lands l ON lc.land_id = l.id
        WHERE lc.land_id = $land_id AND lc.status = 'active'
    ");
    if($result) $certificate = mysqli_fetch_assoc($result);
} elseif($qr_code) {
    // Get by QR code (public verification)
    $result = mysqli_query($conn, "
        SELECT lc.*, l.id as land_id
        FROM land_certificates lc
        JOIN lands l ON lc.land_id = l.id
        WHERE lc.qr_code_data = '$qr_code' AND lc.status = 'active'
    ");
    if($result) $certificate = mysqli_fetch_assoc($result);
}

// If no certificate exists, check if land is eligible for one
if(!$certificate && $land_id) {
    $result = mysqli_query($conn, "
        SELECT l.*, u.full_name as owner_name, u.phone as owner_phone, u.national_id as owner_national_id,
               v.name as village_name, d.name as district_name, r.name as region_name,
               vl.full_name as village_verifier_name, sv.full_name as surveyor_name,
               rs.license_number as surveyor_license
        FROM lands l
        JOIN users u ON l.user_id = u.id
        LEFT JOIN villages v ON l.village_id = v.id
        LEFT JOIN districts d ON l.district_id = d.id
        LEFT JOIN regions r ON l.region_id = r.id
        LEFT JOIN users vl ON l.village_verified_by = vl.id
        LEFT JOIN users sv ON l.surveyor_verified_by = sv.id
        LEFT JOIN registered_surveyors rs ON sv.id = rs.user_id
        WHERE l.id = $land_id
    ");
    $land = mysqli_fetch_assoc($result);

    // Check if land is verified enough for certificate
    $can_generate = false;
    if($land && in_array($land['status'], ['village_verified', 'surveyor_verified', 'fully_verified'])) {
        $can_generate = true;
    }

    // Generate certificate if eligible and user is owner or admin
    if($can_generate && isset($_SESSION['user_id'])) {
        $is_owner = $_SESSION['user_id'] == $land['user_id'];
        $is_admin = $_SESSION['role'] == 'admin';
        $is_village = in_array($_SESSION['role'], ['village_chairman', 'land_officer']);

        if($is_owner || $is_admin || $is_village) {
            // Get beacon points
            $beacon_points = [];
            $bp_result = mysqli_query($conn, "SELECT latitude, longitude, point_order FROM beacon_points WHERE land_id = $land_id ORDER BY point_order");
            while($bp = mysqli_fetch_assoc($bp_result)) {
                $beacon_points[] = $bp;
            }

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

            // Count neighbor verifications
            $nv_result = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM land_neighbors WHERE land_id = $land_id AND confirmation_status = 'confirmed'");
            $neighbor_count = $nv_result ? mysqli_fetch_assoc($nv_result)['cnt'] : 0;

            // Generate certificate number and QR code
            $year = date('Y');
            $count_result = mysqli_query($conn, "SELECT COUNT(*) + 1 as num FROM land_certificates WHERE YEAR(issued_at) = $year");
            $count = $count_result ? mysqli_fetch_assoc($count_result)['num'] : 1;
            $cert_number = "LS-CERT-$year-" . str_pad($count, 6, '0', STR_PAD_LEFT);

            // Generate unique QR code data
            $qr_data = bin2hex(random_bytes(16));

            // Prepare data
            $owner_name = mysqli_real_escape_string($conn, $land['owner_name']);
            $owner_phone = mysqli_real_escape_string($conn, $land['owner_phone']);
            $owner_nid = mysqli_real_escape_string($conn, $land['owner_national_id'] ?? '');
            $land_name = mysqli_real_escape_string($conn, $land['land_name']);
            $village_name = mysqli_real_escape_string($conn, $land['village_name'] ?? '');
            $district_name = mysqli_real_escape_string($conn, $land['district_name'] ?? '');
            $region_name = mysqli_real_escape_string($conn, $land['region_name'] ?? '');
            $boundary_json = mysqli_real_escape_string($conn, json_encode($beacon_points));
            $vv_name = mysqli_real_escape_string($conn, $land['village_verifier_name'] ?? '');
            $sv_name = mysqli_real_escape_string($conn, $land['surveyor_name'] ?? '');
            $sv_license = mysqli_real_escape_string($conn, $land['surveyor_license'] ?? '');

            $sql = "INSERT INTO land_certificates (
                        land_id, certificate_number,
                        owner_name, owner_phone, owner_national_id,
                        land_name, land_size, land_size_unit,
                        village_name, district_name, region_name,
                        boundary_points, center_latitude, center_longitude,
                        neighbor_verifications, village_verified, village_verified_by_name,
                        surveyor_verified, surveyor_name, surveyor_license,
                        qr_code_data, status
                    ) VALUES (
                        $land_id, '$cert_number',
                        '$owner_name', '$owner_phone', " . ($owner_nid ? "'$owner_nid'" : 'NULL') . ",
                        '$land_name', {$land['total_area']}, '{$land['area_unit']}',
                        " . ($village_name ? "'$village_name'" : 'NULL') . ",
                        " . ($district_name ? "'$district_name'" : 'NULL') . ",
                        " . ($region_name ? "'$region_name'" : 'NULL') . ",
                        '$boundary_json', $center_lat, $center_lng,
                        $neighbor_count, " . ($land['village_verified_by'] ? '1' : '0') . ", " . ($vv_name ? "'$vv_name'" : 'NULL') . ",
                        " . ($land['surveyor_verified_by'] ? '1' : '0') . ", " . ($sv_name ? "'$sv_name'" : 'NULL') . ", " . ($sv_license ? "'$sv_license'" : 'NULL') . ",
                        '$qr_data', 'active'
                    )";

            if(mysqli_query($conn, $sql)) {
                // Update land with certificate info
                mysqli_query($conn, "UPDATE lands SET certificate_number = '$cert_number', certificate_issued_at = NOW(), certificate_qr_code = '$qr_data' WHERE id = $land_id");

                // Log history
                mysqli_query($conn, "
                    INSERT INTO land_history (land_id, event_type, event_description, performed_by)
                    VALUES ($land_id, 'certificate_issued', 'Digital certificate $cert_number issued', {$_SESSION['user_id']})
                ");

                // Refresh certificate data
                $result = mysqli_query($conn, "SELECT * FROM land_certificates WHERE land_id = $land_id AND status = 'active'");
                $certificate = mysqli_fetch_assoc($result);
            }
        }
    }
}

// If still no certificate, show error
if(!$certificate) {
    $error_message = "Certificate not found or land not eligible for certificate.";
}

// Generate QR code URL
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
$verify_url = $base_url . "/uhakikimadalali/cbc_certificate?qr=" . ($certificate['qr_code_data'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Digital Land Certificate - <?php echo htmlspecialchars($certificate['certificate_number'] ?? 'Land Secure'); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }

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

        .actions-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
            color: white;
            text-decoration: none;
            font-weight: 600;
            backdrop-filter: blur(10px);
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: rgba(255,255,255,0.3);
            color: white;
        }

        .print-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 24px;
            background: white;
            border-radius: 10px;
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
        }

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

        /* Certificate Styles */
        .certificate {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }

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

        .certificate-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
            pointer-events: none;
        }

        .certificate-header .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 16px;
            margin-bottom: 24px;
            position: relative;
            z-index: 1;
        }

        .certificate-header .logo-icon {
            width: 70px;
            height: 70px;
            background: rgba(255,255,255,0.15);
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255,255,255,0.2);
        }

        .certificate-header .logo-text {
            text-align: left;
        }

        .certificate-header .logo-text h2 {
            font-size: 28px;
            font-weight: 700;
            margin: 0;
        }

        .certificate-header .logo-text span {
            font-size: 14px;
            opacity: 0.8;
        }

        .certificate-title {
            font-family: 'Playfair Display', serif;
            font-size: 36px;
            margin-bottom: 8px;
            position: relative;
            z-index: 1;
        }

        .certificate-subtitle {
            font-size: 16px;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }

        .certificate-number {
            display: inline-block;
            background: rgba(255,255,255,0.2);
            padding: 8px 24px;
            border-radius: 25px;
            margin-top: 16px;
            font-weight: 600;
            font-size: 14px;
            letter-spacing: 1px;
            position: relative;
            z-index: 1;
        }

        .certificate-body {
            padding: 40px;
        }

        .certificate-content {
            display: grid;
            grid-template-columns: 1fr 200px;
            gap: 40px;
        }

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

        .info-section {
            margin-bottom: 30px;
        }

        .info-section-title {
            font-size: 12px;
            font-weight: 600;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .info-section-title i {
            color: #1a3a6e;
        }

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

        .info-item {
            padding: 16px;
            background: #f8f9fa;
            border-radius: 12px;
            border-left: 4px solid #1a3a6e;
        }

        .info-label {
            font-size: 11px;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 4px;
        }

        .info-value {
            font-size: 16px;
            font-weight: 600;
            color: #1a1d21;
        }

        .info-value.large {
            font-size: 24px;
        }

        /* QR Code Section */
        .qr-section {
            text-align: center;
        }

        .qr-code {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 16px;
            margin-bottom: 16px;
        }

        .qr-code img {
            width: 160px;
            height: 160px;
        }

        .qr-label {
            font-size: 12px;
            color: #6c757d;
            margin-bottom: 8px;
        }

        .qr-instruction {
            font-size: 11px;
            color: #6c757d;
            background: #fff3cd;
            padding: 8px 12px;
            border-radius: 8px;
        }

        /* Verification Badges */
        .verification-badges {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-top: 16px;
        }

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

        .badge-verified {
            background: #d4edda;
            color: #155724;
        }

        .badge-neighbors {
            background: #cce5ff;
            color: #004085;
        }

        .badge-surveyor {
            background: #e2d5f1;
            color: #5a3d8a;
        }

        /* GPS Coordinates */
        .gps-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-top: 24px;
        }

        .gps-title {
            font-size: 12px;
            font-weight: 600;
            color: #6c757d;
            text-transform: uppercase;
            margin-bottom: 12px;
        }

        .gps-coords {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 8px;
        }

        .gps-point {
            background: white;
            padding: 10px 14px;
            border-radius: 8px;
            font-size: 12px;
            font-family: monospace;
        }

        .gps-point strong {
            color: #1a3a6e;
        }

        /* Footer */
        .certificate-footer {
            background: #f8f9fa;
            padding: 24px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-top: 2px dashed #dee2e6;
        }

        .footer-text {
            font-size: 12px;
            color: #6c757d;
        }

        .footer-text strong {
            color: #1a1d21;
        }

        .certificate-seal {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #ffd700 0%, #ff8c00 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 32px;
            box-shadow: 0 4px 15px rgba(255, 140, 0, 0.4);
        }

        /* Error State */
        .error-card {
            background: white;
            border-radius: 20px;
            padding: 60px 40px;
            text-align: center;
        }

        .error-icon {
            width: 100px;
            height: 100px;
            background: #f8d7da;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
            font-size: 48px;
            color: #721c24;
        }

        .error-card h2 {
            color: #721c24;
            margin-bottom: 16px;
        }

        .error-card p {
            color: #6c757d;
            margin-bottom: 24px;
        }

        /* Print Styles */
        @media print {
            body {
                background: white;
                padding: 0;
            }

            .actions-bar {
                display: none;
            }

            .certificate {
                box-shadow: none;
                border: 2px solid #1a3a6e;
            }
        }
    </style>
</head>
<body>
    <div class="certificate-container">
        <div class="actions-bar">
            <a href="<?php echo isset($_SESSION['user_id']) ? 'dashboard' : '/'; ?>" class="back-btn">
                <i class="fas fa-arrow-left"></i> Back
            </a>
            <?php if($certificate): ?>
            <button class="print-btn" onclick="window.print()">
                <i class="fas fa-print"></i> Print Certificate
            </button>
            <?php endif; ?>
        </div>

        <?php if($certificate): ?>
        <div class="certificate">
            <!-- Header -->
            <div class="certificate-header">
                <div class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <div class="logo-text">
                        <h2>Land Secure</h2>
                        <span>Digital Land Registry</span>
                    </div>
                </div>
                <h1 class="certificate-title">Digital Land Certificate</h1>
                <p class="certificate-subtitle">Cheti cha Ardhi cha Kidijitali</p>
                <div class="certificate-number">
                    <?php echo htmlspecialchars($certificate['certificate_number']); ?>
                </div>
            </div>

            <!-- Body -->
            <div class="certificate-body">
                <div class="certificate-content">
                    <div class="main-content">
                        <!-- Owner Information -->
                        <div class="info-section">
                            <h3 class="info-section-title">
                                <i class="fas fa-user"></i> Owner Information / Taarifa za Mmiliki
                            </h3>
                            <div class="info-grid">
                                <div class="info-item">
                                    <div class="info-label">Full Name</div>
                                    <div class="info-value"><?php echo htmlspecialchars($certificate['owner_name']); ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Phone Number</div>
                                    <div class="info-value"><?php echo htmlspecialchars($certificate['owner_phone']); ?></div>
                                </div>
                                <?php if($certificate['owner_national_id']): ?>
                                <div class="info-item">
                                    <div class="info-label">National ID</div>
                                    <div class="info-value"><?php echo htmlspecialchars($certificate['owner_national_id']); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Land Information -->
                        <div class="info-section">
                            <h3 class="info-section-title">
                                <i class="fas fa-map-marked-alt"></i> Land Information / Taarifa za Ardhi
                            </h3>
                            <div class="info-grid">
                                <div class="info-item">
                                    <div class="info-label">Land Name</div>
                                    <div class="info-value"><?php echo htmlspecialchars($certificate['land_name']); ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Land Size</div>
                                    <div class="info-value large">
                                        <?php echo number_format($certificate['land_size'], 2); ?>
                                        <small><?php echo strtoupper($certificate['land_size_unit']); ?></small>
                                    </div>
                                </div>
                                <?php if($certificate['village_name']): ?>
                                <div class="info-item">
                                    <div class="info-label">Village</div>
                                    <div class="info-value"><?php echo htmlspecialchars($certificate['village_name']); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if($certificate['district_name']): ?>
                                <div class="info-item">
                                    <div class="info-label">District</div>
                                    <div class="info-value"><?php echo htmlspecialchars($certificate['district_name']); ?></div>
                                </div>
                                <?php endif; ?>
                                <div class="info-item">
                                    <div class="info-label">Center Coordinates</div>
                                    <div class="info-value" style="font-family: monospace; font-size: 13px;">
                                        <?php echo number_format($certificate['center_latitude'], 6); ?>,
                                        <?php echo number_format($certificate['center_longitude'], 6); ?>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Issue Date</div>
                                    <div class="info-value"><?php echo date('F j, Y', strtotime($certificate['issued_at'])); ?></div>
                                </div>
                            </div>

                            <!-- Verification Badges -->
                            <div class="verification-badges">
                                <?php if($certificate['neighbor_verifications'] > 0): ?>
                                <span class="badge badge-neighbors">
                                    <i class="fas fa-users"></i>
                                    <?php echo $certificate['neighbor_verifications']; ?> Neighbor Confirmations
                                </span>
                                <?php endif; ?>

                                <?php if($certificate['village_verified']): ?>
                                <span class="badge badge-verified">
                                    <i class="fas fa-check-circle"></i>
                                    Village Verified
                                    <?php if($certificate['village_verified_by_name']): ?>
                                    (<?php echo htmlspecialchars($certificate['village_verified_by_name']); ?>)
                                    <?php endif; ?>
                                </span>
                                <?php endif; ?>

                                <?php if($certificate['surveyor_verified']): ?>
                                <span class="badge badge-surveyor">
                                    <i class="fas fa-ruler-combined"></i>
                                    Surveyor Verified
                                    <?php if($certificate['surveyor_license']): ?>
                                    (#<?php echo htmlspecialchars($certificate['surveyor_license']); ?>)
                                    <?php endif; ?>
                                </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- GPS Boundary -->
                        <?php
                        $boundary = json_decode($certificate['boundary_points'], true);
                        if($boundary && count($boundary) > 0):
                        ?>
                        <div class="gps-section">
                            <h4 class="gps-title">
                                <i class="fas fa-map-pin"></i> Boundary Coordinates / Vipimo vya Mpaka
                            </h4>
                            <div class="gps-coords">
                                <?php foreach($boundary as $i => $point): ?>
                                <div class="gps-point">
                                    <strong>Point <?php echo $i + 1; ?>:</strong>
                                    <?php echo number_format($point['latitude'], 6); ?>,
                                    <?php echo number_format($point['longitude'], 6); ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- QR Code Section -->
                    <div class="qr-section">
                        <div class="qr-code">
                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=<?php echo urlencode($verify_url); ?>"
                                 alt="Verification QR Code">
                        </div>
                        <p class="qr-label">Scan to Verify</p>
                        <p class="qr-instruction">
                            <i class="fas fa-mobile-alt"></i>
                            Scan this QR code to verify this certificate online
                        </p>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div class="certificate-footer">
                <div class="footer-text">
                    <p><strong>Land Secure Digital Registry</strong></p>
                    <p>This certificate confirms a digital land record within the Land Secure platform.</p>
                    <p style="margin-top: 8px;">
                        <i class="fas fa-info-circle"></i>
                        Certificate ID: <?php echo $certificate['certificate_number']; ?> |
                        Issued: <?php echo date('Y-m-d H:i', strtotime($certificate['issued_at'])); ?>
                    </p>
                </div>
                <div class="certificate-seal">
                    <i class="fas fa-check"></i>
                </div>
            </div>
        </div>
        <?php else: ?>
        <!-- Error State -->
        <div class="error-card">
            <div class="error-icon">
                <i class="fas fa-exclamation-circle"></i>
            </div>
            <h2>Certificate Not Found</h2>
            <p><?php echo $error_message ?? 'The requested certificate could not be found or the land is not eligible for a certificate.'; ?></p>
            <p class="text-muted">Land must be verified by village authority to receive a certificate.</p>
            <a href="<?php echo isset($_SESSION['user_id']) ? 'dashboard' : '/'; ?>" class="back-btn" style="background: #667eea; color: white; display: inline-flex; margin-top: 16px;">
                <i class="fas fa-home"></i> Return Home
            </a>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>
