<?php
/**
 * LandSecure Certificate Verification Page
 * Allows anyone to verify the authenticity of a land certificate
 */

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

$verification_code = isset($_GET['code']) ? trim($_GET['code']) : '';
$is_valid = false;
$certificate_data = null;
$error_message = '';

if(!empty($verification_code)) {
    // Parse the verification code
    // Format: LS-YEAR-XXXXXX-HASHCODE
    $parts = explode('-', $verification_code);

    if(count($parts) >= 4 && $parts[0] === 'LS') {
        $year = $parts[1];
        $land_id_padded = $parts[2];
        $provided_hash = strtoupper($parts[3]);

        // Extract land ID
        $land_id = intval($land_id_padded);

        if($land_id > 0) {
            // Get land details
            $land_sql = "SELECT l.*, u.full_name as owner_name, u.phone as owner_phone,
                         u.email as owner_email, 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 = ?";

            $stmt = mysqli_prepare($conn, $land_sql);
            mysqli_stmt_bind_param($stmt, 'i', $land_id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if($land = mysqli_fetch_assoc($result)) {
                // Regenerate hash to verify
                $certificate_id = 'LS-' . date('Y', strtotime($land['created_at'])) . '-' . str_pad($land['id'], 6, '0', STR_PAD_LEFT);
                $expected_hash = strtoupper(substr(md5($certificate_id . $land['created_at'] . $land['user_id']), 0, 12));

                if($provided_hash === $expected_hash) {
                    $is_valid = true;

                    // Get beacon points count
                    $points_sql = "SELECT COUNT(*) as cnt FROM beacon_points WHERE land_id = ?";
                    $stmt2 = mysqli_prepare($conn, $points_sql);
                    mysqli_stmt_bind_param($stmt2, 'i', $land_id);
                    mysqli_stmt_execute($stmt2);
                    $points_result = mysqli_stmt_get_result($stmt2);
                    $points_count = mysqli_fetch_assoc($points_result)['cnt'];

                    $certificate_data = [
                        'certificate_id' => $certificate_id,
                        'land_id' => $land['id'],
                        'land_name' => $land['land_name'],
                        'owner_name' => $land['owner_name'],
                        'owner_phone' => substr($land['owner_phone'], 0, 4) . '****' . substr($land['owner_phone'], -2),
                        'region' => $land['region_name'],
                        'district' => $land['district_name'],
                        'registration_date' => date('d F Y', strtotime($land['created_at'])),
                        'is_verified' => $land['is_verified'] ?? false,
                        'user_type' => $land['user_type'],
                        'beacon_points' => $points_count
                    ];

                    // Log verification
                    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                    $log_sql = "INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (0, 'certificate_verified', ?, ?)";
                    $log_stmt = mysqli_prepare($conn, $log_sql);
                    $log_details = json_encode(['certificate_id' => $certificate_id, 'land_id' => $land_id]);
                    mysqli_stmt_bind_param($log_stmt, 'ss', $log_details, $ip);
                    @mysqli_stmt_execute($log_stmt);
                } else {
                    $error_message = 'Invalid verification hash. The certificate may have been tampered with.';
                }
            } else {
                $error_message = 'Certificate not found. The land record may have been deleted.';
            }
        } else {
            $error_message = 'Invalid certificate format.';
        }
    } else {
        $error_message = 'Invalid verification code format.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Certificate Verification - LandSecure</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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 50%, #1a3a6e 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .verification-container {
            width: 100%;
            max-width: 600px;
        }

        .verification-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }

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

        .card-header::after {
            content: '';
            display: block;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, #d4af37, #f5d77a, #d4af37);
            margin-top: 30px;
            margin-bottom: -30px;
        }

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

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

        .card-title {
            font-family: 'Playfair Display', serif;
            font-size: 24px;
            margin-bottom: 5px;
        }

        .card-subtitle {
            font-size: 14px;
            opacity: 0.9;
        }

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

        /* Search Form */
        .search-form {
            margin-bottom: 30px;
        }

        .search-form label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #64748b;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .search-input-group {
            display: flex;
            gap: 10px;
        }

        .search-input-group input {
            flex: 1;
            padding: 15px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            font-family: monospace;
            transition: all 0.3s;
        }

        .search-input-group input:focus {
            outline: none;
            border-color: #1a3a6e;
            box-shadow: 0 0 0 4px rgba(26, 58, 110, 0.1);
        }

        .btn-verify {
            padding: 15px 25px;
            background: linear-gradient(135deg, #1a3a6e, #2d5a3d);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .btn-verify:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(26, 58, 110, 0.4);
        }

        /* Result States */
        .result-box {
            border-radius: 16px;
            padding: 30px;
            text-align: center;
        }

        .result-valid {
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(22, 163, 74, 0.1));
            border: 2px solid #22c55e;
        }

        .result-invalid {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.1), rgba(220, 38, 38, 0.1));
            border: 2px solid #ef4444;
        }

        .result-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }

        .result-valid .result-icon {
            background: #22c55e;
        }

        .result-invalid .result-icon {
            background: #ef4444;
        }

        .result-icon i {
            font-size: 40px;
            color: white;
        }

        .result-title {
            font-family: 'Playfair Display', serif;
            font-size: 22px;
            margin-bottom: 10px;
        }

        .result-valid .result-title {
            color: #16a34a;
        }

        .result-invalid .result-title {
            color: #dc2626;
        }

        .result-subtitle {
            font-size: 14px;
            color: #64748b;
            margin-bottom: 25px;
        }

        /* Certificate Details */
        .certificate-details {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            text-align: left;
            margin-top: 20px;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-size: 13px;
            color: #64748b;
            font-weight: 500;
        }

        .detail-value {
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
            text-align: right;
        }

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

        .badge-verified {
            background: rgba(34, 197, 94, 0.15);
            color: #16a34a;
        }

        .badge-registered {
            background: rgba(59, 130, 246, 0.15);
            color: #2563eb;
        }

        .badge-premium {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(217, 119, 6, 0.15));
            color: #d97706;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
        }

        .empty-state i {
            font-size: 60px;
            color: #d4af37;
            margin-bottom: 20px;
        }

        .empty-state h3 {
            font-family: 'Playfair Display', serif;
            font-size: 20px;
            color: #1a3a6e;
            margin-bottom: 10px;
        }

        .empty-state p {
            font-size: 14px;
            color: #64748b;
            line-height: 1.6;
        }

        /* Footer */
        .card-footer {
            background: #f8fafc;
            padding: 20px 30px;
            text-align: center;
            border-top: 1px solid #e2e8f0;
        }

        .footer-text {
            font-size: 12px;
            color: #64748b;
        }

        .footer-text a {
            color: #1a3a6e;
            text-decoration: none;
            font-weight: 600;
        }

        .footer-seal {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }

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

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

        /* Responsive */
        @media (max-width: 480px) {
            .search-input-group {
                flex-direction: column;
            }

            .card-header {
                padding: 25px 20px;
            }

            .card-body {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="verification-container">
        <div class="verification-card">
            <div class="card-header">
                <div class="logo-icon">
                    <i class="fas fa-shield-alt"></i>
                </div>
                <h1 class="card-title">LandSecure</h1>
                <p class="card-subtitle">Certificate Verification Portal</p>
            </div>

            <div class="card-body">
                <form class="search-form" method="GET" action="">
                    <label>Enter Verification Code</label>
                    <div class="search-input-group">
                        <input type="text" name="code" placeholder="LS-2024-000001-A1B2C3D4E5F6"
                               value="<?php echo htmlspecialchars($verification_code); ?>" required>
                        <button type="submit" class="btn-verify">
                            <i class="fas fa-search"></i>
                            Verify
                        </button>
                    </div>
                </form>

                <?php if($is_valid && $certificate_data): ?>
                    <!-- Valid Certificate -->
                    <div class="result-box result-valid">
                        <div class="result-icon">
                            <i class="fas fa-check"></i>
                        </div>
                        <h2 class="result-title">Certificate Verified</h2>
                        <p class="result-subtitle">This is an authentic LandSecure certificate</p>

                        <div class="certificate-details">
                            <div class="detail-row">
                                <span class="detail-label">Certificate ID</span>
                                <span class="detail-value"><?php echo $certificate_data['certificate_id']; ?></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Land Name</span>
                                <span class="detail-value"><?php echo htmlspecialchars($certificate_data['land_name']); ?></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Owner</span>
                                <span class="detail-value"><?php echo htmlspecialchars($certificate_data['owner_name']); ?></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Phone (Partial)</span>
                                <span class="detail-value"><?php echo $certificate_data['owner_phone']; ?></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Location</span>
                                <span class="detail-value">
                                    <?php
                                    $loc = [];
                                    if($certificate_data['district']) $loc[] = $certificate_data['district'];
                                    if($certificate_data['region']) $loc[] = $certificate_data['region'];
                                    echo htmlspecialchars(implode(', ', $loc) ?: 'Not specified');
                                    ?>
                                </span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Beacon Points</span>
                                <span class="detail-value"><?php echo $certificate_data['beacon_points']; ?> points</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Registration Date</span>
                                <span class="detail-value"><?php echo $certificate_data['registration_date']; ?></span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Status</span>
                                <span class="detail-value">
                                    <?php if($certificate_data['is_verified']): ?>
                                        <span class="verification-badge badge-verified">
                                            <i class="fas fa-check-circle"></i> Surveyor Verified
                                        </span>
                                    <?php else: ?>
                                        <span class="verification-badge badge-registered">
                                            <i class="fas fa-user-check"></i> User Registered
                                        </span>
                                    <?php endif; ?>
                                </span>
                            </div>
                            <?php if($certificate_data['user_type'] == 'premium'): ?>
                            <div class="detail-row">
                                <span class="detail-label">Account Type</span>
                                <span class="detail-value">
                                    <span class="verification-badge badge-premium">
                                        <i class="fas fa-crown"></i> Premium
                                    </span>
                                </span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                <?php elseif(!empty($verification_code)): ?>
                    <!-- Invalid Certificate -->
                    <div class="result-box result-invalid">
                        <div class="result-icon">
                            <i class="fas fa-times"></i>
                        </div>
                        <h2 class="result-title">Verification Failed</h2>
                        <p class="result-subtitle"><?php echo htmlspecialchars($error_message); ?></p>
                    </div>

                <?php else: ?>
                    <!-- Empty State -->
                    <div class="empty-state">
                        <i class="fas fa-qrcode"></i>
                        <h3>Verify a Certificate</h3>
                        <p>Enter the verification code from a LandSecure certificate or scan the QR code to verify its authenticity.</p>
                    </div>
                <?php endif; ?>
            </div>

            <div class="card-footer">
                <p class="footer-text">
                    Need help? <a href="contact">Contact us</a> |
                    <a href="<?php echo url(''); ?>">Visit LandSecure</a>
                </p>
                <div class="footer-seal">
                    <i class="fas fa-shield-alt"></i>
                    <span>LandSecure Digital Registry</span>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
