<?php
/**
 * Public Land Verification Page
 * Accessed via QR code or direct link
 * Shows land ownership details (privacy protected)
 */

// Database connection
$is_production = (
    isset($_SERVER['HTTP_HOST']) &&
    (strpos($_SERVER['HTTP_HOST'], 'landsecure.co.tz') !== false ||
     strpos($_SERVER['HTTP_HOST'], 'landsecure') !== false)
);

if ($is_production) {
    $db_host = 'localhost';
    $db_user = 'pitechco_mylands';
    $db_pass = 'RomilusK>%+66';
    $db_name = 'pitechco_mylands';
} else {
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'land_survey_db';
}

$conn = @mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
    die("Database connection failed");
}
mysqli_set_charset($conn, "utf8mb4");

// Handle report submission
$report_success = false;
$report_error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'report_fraud') {
    $report_land_id = intval($_POST['land_id'] ?? 0);
    $reporter_name = mysqli_real_escape_string($conn, trim($_POST['reporter_name'] ?? ''));
    $reporter_phone = mysqli_real_escape_string($conn, trim($_POST['reporter_phone'] ?? ''));
    $report_details = mysqli_real_escape_string($conn, trim($_POST['report_details'] ?? ''));

    if ($report_land_id > 0 && $reporter_phone && $report_details) {
        // Check if land_fraud_reports table exists, create if not
        $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_fraud_reports'");
        if (mysqli_num_rows($tableCheck) == 0) {
            mysqli_query($conn, "CREATE TABLE land_fraud_reports (
                id INT AUTO_INCREMENT PRIMARY KEY,
                land_id INT NOT NULL,
                reporter_name VARCHAR(255),
                reporter_phone VARCHAR(50) NOT NULL,
                report_details TEXT NOT NULL,
                status ENUM('pending', 'investigating', 'resolved', 'dismissed') DEFAULT 'pending',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_land_id (land_id),
                INDEX idx_status (status)
            )");
        }

        $insertReport = mysqli_query($conn, "INSERT INTO land_fraud_reports (land_id, reporter_name, reporter_phone, report_details)
                                             VALUES ($report_land_id, '$reporter_name', '$reporter_phone', '$report_details')");
        if ($insertReport) {
            $report_id = mysqli_insert_id($conn);
            $report_success = true;

            // Get land owner info
            $landOwnerQuery = mysqli_query($conn, "SELECT l.user_id, l.land_name, l.village_id, u.full_name as owner_name
                                                    FROM lands l
                                                    JOIN users u ON l.user_id = u.id
                                                    WHERE l.id = $report_land_id");
            if ($landOwnerQuery && $landOwnerRow = mysqli_fetch_assoc($landOwnerQuery)) {
                $ownerId = $landOwnerRow['user_id'];
                $landName = $landOwnerRow['land_name'] ?? 'Land #' . $report_land_id;
                $villageId = intval($landOwnerRow['village_id'] ?? 0);

                // Create notification for land owner (don't show reporter info)
                $notifTitle = "Tahadhari: Ripoti ya Shaka / Alert: Fraud Report";
                $notifMessage = "Mtu amefungua ripoti ya shaka kuhusu ardhi yako \"{$landName}\". ";
                $notifMessage .= "Ripoti inaendelea kuchunguzwa. / Someone has filed a doubt report about your land. The report is being investigated.";
                $notifTitle = mysqli_real_escape_string($conn, $notifTitle);
                $notifMessage = mysqli_real_escape_string($conn, $notifMessage);

                mysqli_query($conn, "INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, metadata, created_at)
                                     VALUES ($ownerId, 'fraud_report', '$notifTitle', '$notifMessage', $report_land_id, '{\"report_id\": $report_id}', NOW())");

                // Notify admins and payment admins
                $adminQuery = mysqli_query($conn, "SELECT id FROM users WHERE role IN ('admin', 'payment_admin') AND status = 'active'");
                while ($admin = mysqli_fetch_assoc($adminQuery)) {
                    $adminTitle = "Ripoti Mpya ya Uuzwaji wa Mara Mbili / New Double Sale Report";
                    $adminMessage = "Ripoti mpya imefunguliwa kwa ardhi \"{$landName}\" (ID: LS-" . str_pad($report_land_id, 5, '0', STR_PAD_LEFT) . "). ";
                    $adminMessage .= "Tafadhali chunguza na kuchukua hatua. / A new fraud report has been filed. Please investigate.";
                    $adminTitle = mysqli_real_escape_string($conn, $adminTitle);
                    $adminMessage = mysqli_real_escape_string($conn, $adminMessage);

                    mysqli_query($conn, "INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, metadata, created_at)
                                         VALUES ({$admin['id']}, 'fraud_report_admin', '$adminTitle', '$adminMessage', $report_land_id, '{\"report_id\": $report_id}', NOW())");
                }

                // Notify village officials (chairman, land officer)
                if ($villageId > 0) {
                    $officialQuery = mysqli_query($conn, "SELECT id FROM users WHERE village_id = $villageId AND role IN ('village_chairman', 'land_officer') AND status = 'active'");
                    while ($official = mysqli_fetch_assoc($officialQuery)) {
                        $officialTitle = "Ripoti ya Mgogoro wa Ardhi / Land Dispute Report";
                        $officialMessage = "Ripoti ya shaka ya uuzwaji mara mbili imefunguliwa kwa ardhi \"{$landName}\" katika eneo lako. ";
                        $officialMessage .= "Tafadhali chunguza. / A double sale report has been filed for land in your area.";
                        $officialTitle = mysqli_real_escape_string($conn, $officialTitle);
                        $officialMessage = mysqli_real_escape_string($conn, $officialMessage);

                        mysqli_query($conn, "INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, metadata, created_at)
                                             VALUES ({$official['id']}, 'fraud_report_official', '$officialTitle', '$officialMessage', $report_land_id, '{\"report_id\": $report_id}', NOW())");
                    }
                }
            }
        } else {
            $report_error = "Imeshindwa kutuma ripoti. Tafadhali jaribu tena.";
        }
    } else {
        $report_error = "Tafadhali jaza nambari ya simu na maelezo ya ripoti.";
    }
}

// Get parameters
$land_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$qr_code = isset($_GET['qr']) ? $_GET['qr'] : null;
$verification_code = isset($_GET['code']) ? $_GET['code'] : null;

$land = null;
$error = null;

// Get land columns
$landsColumns = array();
$colsResult = mysqli_query($conn, "SHOW COLUMNS FROM lands");
if ($colsResult) {
    while ($col = mysqli_fetch_assoc($colsResult)) {
        $landsColumns[] = strtolower($col['Field']);
    }
}

// Determine column names
$landNameCol = in_array('name', $landsColumns) ? 'name' : 'land_name';
$hasStatus = in_array('status', $landsColumns);
$hasRegionId = in_array('region_id', $landsColumns);
$hasDistrictId = in_array('district_id', $landsColumns);
$hasVillageId = in_array('village_id', $landsColumns);

// Check if regions and districts tables exist
$regionsExist = false;
$districtsExist = false;
$villagesExist = false;

$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'regions'");
if ($tableCheck && mysqli_num_rows($tableCheck) > 0) $regionsExist = true;

$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'districts'");
if ($tableCheck && mysqli_num_rows($tableCheck) > 0) $districtsExist = true;

$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'villages'");
if ($tableCheck && mysqli_num_rows($tableCheck) > 0) $villagesExist = true;

// Build query with region/district joins
$selectFields = "l.*, l.$landNameCol as land_name, u.full_name as owner_name, u.phone as owner_phone";
$joins = "JOIN users u ON l.user_id = u.id";

if ($hasRegionId && $regionsExist) {
    $selectFields .= ", r.name as region_name";
    $joins .= " LEFT JOIN regions r ON l.region_id = r.id";
}
if ($hasDistrictId && $districtsExist) {
    $selectFields .= ", d.name as district_name";
    $joins .= " LEFT JOIN districts d ON l.district_id = d.id";
}
if ($hasVillageId && $villagesExist) {
    $selectFields .= ", v.name as village_name";
    $joins .= " LEFT JOIN villages v ON l.village_id = v.id";
}

// Find land by ID
if ($land_id > 0) {
    $query = "SELECT $selectFields FROM lands l $joins WHERE l.id = $land_id";
    $result = mysqli_query($conn, $query);
    if ($result) {
        $land = mysqli_fetch_assoc($result);
    }
} elseif ($qr_code || $verification_code) {
    $code = mysqli_real_escape_string($conn, $qr_code ? $qr_code : $verification_code);

    // Try to extract numeric ID from LS-XXXXX format
    if (preg_match('/^LS-?0*(\d+)$/i', $code, $matches)) {
        $extractedId = intval($matches[1]);
        $query = "SELECT $selectFields FROM lands l $joins WHERE l.id = $extractedId";
        $result = mysqli_query($conn, $query);
        if ($result) {
            $land = mysqli_fetch_assoc($result);
        }
    }
}

// Set defaults for missing data
if ($land) {
    if (!isset($land['status'])) {
        $land['status'] = 'pending';
    }
    $land['confirmed_neighbors'] = 0;
    $land['cbc_verified_date'] = null;
    if (!isset($land['village_name'])) $land['village_name'] = $land['village'] ?? null;
    if (!isset($land['district_name'])) $land['district_name'] = null;
    if (!isset($land['region_name'])) $land['region_name'] = null;
}

if (!$land && ($land_id > 0 || $qr_code || $verification_code)) {
    $error = "Ardhi haijapatikana. Hakikisha QR code au nambari ya uthibitisho ni sahihi.";
}

// Privacy protection functions
function maskName($fullName) {
    $parts = explode(' ', trim($fullName));
    $masked = array();
    foreach ($parts as $part) {
        if (strlen($part) > 0) {
            $masked[] = strtoupper(substr($part, 0, 1)) . '.';
        }
    }
    return implode(' ', $masked);
}

function maskPhone($phone) {
    if (strlen($phone) < 4) return 'xxxx';
    return 'xxxxxx' . substr($phone, -4);
}

function generateLandId($id) {
    return 'LS-' . str_pad($id, 5, '0', STR_PAD_LEFT);
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Uthibitisho wa Ardhi - LandSecure</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Inter', sans-serif;
    }

    body {
        background: linear-gradient(135deg, #1e3a5f 0%, #0d1b2a 100%);
        min-height: 100vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px;
    }

    .header {
        text-align: center;
        margin-bottom: 24px;
    }

    .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        margin-bottom: 8px;
    }

    .logo-icon {
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
    }

    .logo-text {
        font-size: 28px;
        font-weight: 700;
        color: white;
    }

    .header p {
        color: rgba(255,255,255,0.7);
        font-size: 14px;
    }

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

    .card-header {
        padding: 24px;
        text-align: center;
    }

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

    .card-header.pending {
        background: linear-gradient(135deg, #f97316, #ea580c);
        color: white;
    }

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

    .status-icon {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 16px;
        font-size: 40px;
    }

    .card-header h2 {
        font-size: 22px;
        margin-bottom: 4px;
    }

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

    .land-id {
        display: inline-block;
        background: rgba(255,255,255,0.2);
        padding: 8px 20px;
        border-radius: 20px;
        font-size: 18px;
        font-weight: 700;
        margin-top: 12px;
        letter-spacing: 1px;
    }

    .card-body {
        padding: 24px;
    }

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

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

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

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

    .info-label {
        color: #64748b;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

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

    .verification-badges {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
    }

    .verification-badge {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        background: #f8fafc;
        border-radius: 10px;
        flex: 1;
        min-width: 120px;
    }

    .verification-badge i {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
    }

    .verification-badge.active i {
        background: rgba(34, 197, 94, 0.1);
        color: #22c55e;
    }

    .verification-badge.inactive i {
        background: rgba(100, 116, 139, 0.1);
        color: #64748b;
    }

    .verification-badge span {
        font-size: 12px;
        color: #64748b;
    }

    .verification-badge strong {
        display: block;
        font-size: 13px;
        color: #1e293b;
    }

    .timestamp {
        text-align: center;
        padding: 16px;
        background: #f8fafc;
        border-top: 1px solid #e2e8f0;
        font-size: 12px;
        color: #64748b;
    }

    .error-card {
        text-align: center;
        padding: 48px 24px;
    }

    .error-icon {
        width: 80px;
        height: 80px;
        background: rgba(239, 68, 68, 0.1);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px;
        font-size: 36px;
        color: #ef4444;
    }

    .error-card h3 {
        color: #1e293b;
        margin-bottom: 8px;
    }

    .error-card p {
        color: #64748b;
        margin-bottom: 24px;
    }

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

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

    .btn-outline {
        background: transparent;
        border: 2px solid #e2e8f0;
        color: #64748b;
    }

    .footer-links {
        margin-top: 24px;
        text-align: center;
    }

    .footer-links a {
        color: rgba(255,255,255,0.7);
        text-decoration: none;
        font-size: 14px;
        margin: 0 12px;
    }

    .privacy-note {
        background: rgba(59, 130, 246, 0.1);
        border: 1px solid rgba(59, 130, 246, 0.2);
        border-radius: 10px;
        padding: 12px 16px;
        margin-top: 16px;
        display: flex;
        align-items: flex-start;
        gap: 10px;
    }

    .privacy-note i {
        color: #3b82f6;
        margin-top: 2px;
    }

    .privacy-note p {
        font-size: 12px;
        color: #64748b;
        margin: 0;
    }

    .search-form {
        margin-top: 20px;
    }

    .search-form .form-group {
        margin-bottom: 16px;
    }

    .search-form label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: #64748b;
        margin-bottom: 8px;
    }

    .search-form input {
        width: 100%;
        padding: 14px 16px;
        border: 2px solid #e2e8f0;
        border-radius: 12px;
        font-size: 16px;
        text-transform: uppercase;
    }

    .search-form input:focus {
        outline: none;
        border-color: #667eea;
    }

    .btn-block {
        width: 100%;
        justify-content: center;
    }

    .divider {
        display: flex;
        align-items: center;
        margin: 24px 0;
    }

    .divider::before,
    .divider::after {
        content: '';
        flex: 1;
        height: 1px;
        background: #e2e8f0;
    }

    .divider span {
        padding: 0 16px;
        color: #94a3b8;
        font-size: 13px;
    }

    .error-actions {
        display: flex;
        gap: 12px;
        justify-content: center;
        flex-wrap: wrap;
    }

    @media (max-width: 480px) {
        .verification-badges {
            flex-direction: column;
        }
    }

    .location-info {
        background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
        border: 1px solid #bae6fd;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 20px;
    }

    .location-info .location-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 0;
        border-bottom: 1px dashed #bae6fd;
    }

    .location-info .location-item:last-child {
        border-bottom: none;
    }

    .location-info .location-item i {
        width: 28px;
        height: 28px;
        background: white;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #0284c7;
        font-size: 12px;
    }

    .location-info .location-item .label {
        font-size: 12px;
        color: #64748b;
    }

    .location-info .location-item .value {
        font-size: 14px;
        font-weight: 600;
        color: #0c4a6e;
    }

    .report-section {
        background: linear-gradient(135deg, #fef2f2, #fee2e2);
        border: 1px solid #fecaca;
        border-radius: 12px;
        padding: 16px;
        margin-top: 20px;
    }

    .report-section .report-header {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 12px;
        cursor: pointer;
    }

    .report-section .report-header i.icon {
        width: 36px;
        height: 36px;
        background: #dc2626;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 16px;
    }

    .report-section .report-header h4 {
        color: #991b1b;
        font-size: 14px;
        margin: 0;
    }

    .report-section .report-header p {
        color: #b91c1c;
        font-size: 12px;
        margin: 0;
    }

    .report-section .report-header .toggle-icon {
        margin-left: auto;
        color: #dc2626;
        transition: transform 0.3s ease;
    }

    .report-section .report-header.open .toggle-icon {
        transform: rotate(180deg);
    }

    .report-form {
        display: none;
        padding-top: 12px;
        border-top: 1px dashed #fecaca;
    }

    .report-form.show {
        display: block;
    }

    .report-form .form-group {
        margin-bottom: 12px;
    }

    .report-form label {
        display: block;
        font-size: 12px;
        font-weight: 600;
        color: #991b1b;
        margin-bottom: 6px;
    }

    .report-form input,
    .report-form textarea {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #fecaca;
        border-radius: 8px;
        font-size: 14px;
        background: white;
    }

    .report-form input:focus,
    .report-form textarea:focus {
        outline: none;
        border-color: #dc2626;
    }

    .report-form textarea {
        min-height: 80px;
        resize: vertical;
    }

    .btn-danger {
        background: linear-gradient(135deg, #dc2626, #b91c1c);
        color: white;
    }

    .btn-danger:hover {
        background: linear-gradient(135deg, #b91c1c, #991b1b);
    }

    .alert {
        padding: 12px 16px;
        border-radius: 10px;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .alert-success {
        background: #dcfce7;
        border: 1px solid #86efac;
        color: #166534;
    }

    .alert-error {
        background: #fee2e2;
        border: 1px solid #fecaca;
        color: #991b1b;
    }

    .alert i {
        font-size: 18px;
    }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">
            <div class="logo-icon">
                <i class="fas fa-shield-alt"></i>
            </div>
            <span class="logo-text">LandSecure</span>
        </div>
        <p>Mfumo wa Uthibitisho wa Umiliki wa Ardhi</p>
    </div>

    <?php if (!$land_id && !$qr_code && !$verification_code): ?>
    <!-- Search Form -->
    <div class="verification-card">
        <div class="card-header search-header">
            <div class="status-icon">
                <i class="fas fa-qrcode"></i>
            </div>
            <h2>Thibitisha Umiliki wa Ardhi</h2>
            <p>Ingiza nambari ya uthibitisho</p>
        </div>

        <div class="card-body">
            <form action="verify-land" method="GET" class="search-form">
                <div class="form-group">
                    <label><i class="fas fa-hashtag"></i> Nambari ya Uthibitisho</label>
                    <input type="text" name="code" placeholder="Mfano: LS-00001" required>
                </div>
                <button type="submit" class="btn btn-primary btn-block">
                    <i class="fas fa-search"></i> Tafuta Ardhi
                </button>
            </form>

            <div class="privacy-note">
                <i class="fas fa-info-circle"></i>
                <p>Ingiza nambari ya uthibitisho iliyopo kwenye hati ya ardhi au QR code.</p>
            </div>
        </div>
    </div>

    <?php elseif ($error): ?>
    <!-- Error -->
    <div class="verification-card">
        <div class="error-card">
            <div class="error-icon">
                <i class="fas fa-search"></i>
            </div>
            <h3>Ardhi Haijapatikana</h3>
            <p><?php echo htmlspecialchars($error); ?></p>
            <div class="error-actions">
                <a href="verify-land" class="btn btn-primary">
                    <i class="fas fa-redo"></i> Jaribu Tena
                </a>
                <a href="scan-location" class="btn btn-outline">
                    <i class="fas fa-map-marker-alt"></i> Scan Eneo
                </a>
            </div>
        </div>
    </div>

    <?php else: ?>
    <!-- Land Found -->
    <div class="verification-card">
        <?php
        $isVerified = ($land['status'] === 'verified' || $land['status'] === 'approved');
        $headerClass = $isVerified ? 'verified' : 'pending';
        ?>
        <div class="card-header <?php echo $headerClass; ?>">
            <div class="status-icon">
                <i class="fas fa-<?php echo $isVerified ? 'check-circle' : 'clock'; ?>"></i>
            </div>
            <h2><?php echo $isVerified ? 'Ardhi Imethibitishwa' : 'Inasubiri Uthibitisho'; ?></h2>
            <p><?php echo $isVerified ? 'Umiliki umethibitishwa rasmi' : 'Uthibitisho unaendelea'; ?></p>
            <div class="land-id"><?php echo generateLandId($land['id']); ?></div>
        </div>

        <div class="card-body">
            <?php if ($report_success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span>Asante! Ripoti yako imepokelewa na itachunguzwa.</span>
            </div>
            <?php elseif ($report_error): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?php echo htmlspecialchars($report_error); ?></span>
            </div>
            <?php endif; ?>

            <!-- Owner Information -->
            <div class="info-section">
                <div class="section-title">
                    <i class="fas fa-user"></i> Taarifa za Mmiliki
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-user-circle"></i> Mmiliki</span>
                    <span class="info-value"><?php echo maskName($land['owner_name']); ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-phone"></i> Simu</span>
                    <span class="info-value"><?php echo maskPhone($land['owner_phone']); ?></span>
                </div>
            </div>

            <!-- Location Information -->
            <?php if ($land['region_name'] || $land['district_name'] || $land['village_name']): ?>
            <div class="location-info">
                <div class="section-title" style="margin-bottom: 8px;">
                    <i class="fas fa-map-marker-alt"></i> Eneo la Ardhi
                </div>
                <?php if ($land['region_name']): ?>
                <div class="location-item">
                    <i class="fas fa-globe-africa"></i>
                    <div>
                        <span class="label">Mkoa</span>
                        <span class="value"><?php echo htmlspecialchars($land['region_name']); ?></span>
                    </div>
                </div>
                <?php endif; ?>
                <?php if ($land['district_name']): ?>
                <div class="location-item">
                    <i class="fas fa-city"></i>
                    <div>
                        <span class="label">Wilaya</span>
                        <span class="value"><?php echo htmlspecialchars($land['district_name']); ?></span>
                    </div>
                </div>
                <?php endif; ?>
                <?php if ($land['village_name']): ?>
                <div class="location-item">
                    <i class="fas fa-home"></i>
                    <div>
                        <span class="label">Kijiji/Mtaa</span>
                        <span class="value"><?php echo htmlspecialchars($land['village_name']); ?></span>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Land Information -->
            <div class="info-section">
                <div class="section-title">
                    <i class="fas fa-map"></i> Taarifa za Ardhi
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-tag"></i> Jina</span>
                    <span class="info-value"><?php echo htmlspecialchars($land['land_name']); ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label"><i class="fas fa-calendar"></i> Ilisajiliwa</span>
                    <span class="info-value"><?php echo date('d M Y', strtotime($land['created_at'])); ?></span>
                </div>
            </div>

            <!-- Verification Status -->
            <div class="info-section">
                <div class="section-title">
                    <i class="fas fa-shield-alt"></i> Hali ya Uthibitisho
                </div>
                <div class="verification-badges">
                    <div class="verification-badge <?php echo $isVerified ? 'active' : 'inactive'; ?>">
                        <i class="fas fa-clipboard-check"></i>
                        <div>
                            <span>Hali</span>
                            <strong><?php echo $isVerified ? 'Imethibitishwa' : 'Inasubiri'; ?></strong>
                        </div>
                    </div>
                    <div class="verification-badge inactive">
                        <i class="fas fa-users"></i>
                        <div>
                            <span>Majirani</span>
                            <strong><?php echo $land['confirmed_neighbors']; ?> Wamethibitisha</strong>
                        </div>
                    </div>
                </div>
            </div>

            <div class="privacy-note">
                <i class="fas fa-info-circle"></i>
                <p>Kwa usalama, taarifa za mmiliki zimefichwaa kwa sehemu. Wasiliana na LandSecure kwa taarifa kamili.</p>
            </div>

            <!-- Report Fraud Section -->
            <div class="report-section">
                <div class="report-header" onclick="toggleReportForm()">
                    <i class="icon fas fa-exclamation-triangle"></i>
                    <div>
                        <h4>Ripoti Uuzwaji wa Mara Mbili</h4>
                        <p>Una shaka kuhusu ardhi hii?</p>
                    </div>
                    <i class="toggle-icon fas fa-chevron-down"></i>
                </div>
                <form class="report-form" id="reportForm" method="POST" action="">
                    <input type="hidden" name="action" value="report_fraud">
                    <input type="hidden" name="land_id" value="<?php echo $land['id']; ?>">

                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Jina Lako (si lazima)</label>
                        <input type="text" name="reporter_name" placeholder="Ingiza jina lako">
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-phone"></i> Nambari ya Simu *</label>
                        <input type="tel" name="reporter_phone" placeholder="Mfano: 0712345678" required>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-comment-alt"></i> Maelezo ya Ripoti *</label>
                        <textarea name="report_details" placeholder="Eleza kwa nini unadhani ardhi hii imeuzwa mara mbili au kuna tatizo lingine..." required></textarea>
                    </div>

                    <button type="submit" class="btn btn-danger btn-block">
                        <i class="fas fa-paper-plane"></i> Tuma Ripoti
                    </button>
                </form>
            </div>
        </div>

        <div class="timestamp">
            <i class="fas fa-clock"></i>
            Imethibitishwa: <?php echo date('d M Y, H:i:s'); ?>
        </div>
    </div>
    <?php endif; ?>

    <div class="footer-links">
        <a href="home"><i class="fas fa-home"></i> Nyumbani</a>
        <a href="scan-location"><i class="fas fa-map-marker-alt"></i> Scan Eneo</a>
        <a href="login"><i class="fas fa-sign-in-alt"></i> Ingia</a>
    </div>

    <script>
    function toggleReportForm() {
        const form = document.getElementById('reportForm');
        const header = document.querySelector('.report-header');

        if (form.classList.contains('show')) {
            form.classList.remove('show');
            header.classList.remove('open');
        } else {
            form.classList.add('show');
            header.classList.add('open');
        }
    }

    // Show form if there was an error
    <?php if ($report_error): ?>
    document.addEventListener('DOMContentLoaded', function() {
        toggleReportForm();
    });
    <?php endif; ?>
    </script>
</body>
</html>
