<?php
/**
 * Village Land Verification Page
 * Allows village leaders to approve or reject land registrations
 */

session_start();
require_once '../db_connect.php';

// Check if user has verification rights
$allowed_roles = ['village_chairman', 'land_officer', 'district_officer'];
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: ../login');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$village_id = $_SESSION['village_id'] ?? null;

$land_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message = '';
$error = '';

// Get land details
$land = null;
if($land_id) {
    $sql = "
        SELECT l.*, u.full_name as owner_name, u.phone as owner_phone, u.email as owner_email,
               v.name as village_name, d.name as district_name, r.name as region_name
        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
        WHERE l.id = $land_id
    ";

    // Restrict to village if not district officer
    if($user_role !== 'district_officer' && $village_id) {
        $sql .= " AND l.village_id = $village_id";
    }

    $result = mysqli_query($conn, $sql);
    $land = mysqli_fetch_assoc($result);
}

if(!$land) {
    header('Location: pending_lands');
    exit;
}

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

// Get neighbor confirmations
$neighbors = [];
$result = mysqli_query($conn, "
    SELECT ln.*, u.full_name as neighbor_name_user
    FROM land_neighbors ln
    LEFT JOIN users u ON ln.neighbor_user_id = u.id
    WHERE ln.land_id = $land_id
    ORDER BY ln.neighbor_direction
");
while($row = mysqli_fetch_assoc($result)) {
    $neighbors[] = $row;
}

// Get land history
$history = [];
$result = mysqli_query($conn, "
    SELECT lh.*, u.full_name as performed_by_name
    FROM land_history lh
    LEFT JOIN users u ON lh.performed_by = u.id
    WHERE lh.land_id = $land_id
    ORDER BY lh.created_at DESC
");
while($row = mysqli_fetch_assoc($result)) {
    $history[] = $row;
}

// Handle verification action
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if($action === 'approve') {
        // Approve the land
        $new_status = 'village_verified';

        // Update land status
        $sql = "UPDATE lands SET
                    status = '$new_status',
                    village_verified_by = $user_id,
                    village_verified_at = NOW(),
                    village_rejection_reason = NULL
                WHERE id = $land_id";

        if(mysqli_query($conn, $sql)) {
            // Log history
            $desc = mysqli_real_escape_string($conn, "Land approved by village " . $user_role);
            mysqli_query($conn, "
                INSERT INTO land_history (land_id, event_type, event_description, performed_by, performed_by_role)
                VALUES ($land_id, 'village_approved', '$desc', $user_id, '$user_role')
            ");

            // Send notification to owner
            $title = mysqli_real_escape_string($conn, "Land Approved - Ardhi Imehakikiwa");
            $msg = mysqli_real_escape_string($conn, "Your land '{$land['land_name']}' has been approved by the village authority.");
            mysqli_query($conn, "
                INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id)
                VALUES ({$land['user_id']}, 'village_approved', '$title', '$msg', $land_id)
            ");

            $message = "Land has been approved successfully!";
            // Refresh land data
            $result = mysqli_query($conn, "SELECT * FROM lands WHERE id = $land_id");
            $land = mysqli_fetch_assoc($result);
        } else {
            $error = "Failed to approve land: " . mysqli_error($conn);
        }
    }
    elseif($action === 'reject') {
        $rejection_reason = mysqli_real_escape_string($conn, $_POST['rejection_reason'] ?? '');

        if(empty($rejection_reason)) {
            $error = "Please provide a reason for rejection";
        } else {
            $sql = "UPDATE lands SET
                        status = 'rejected',
                        village_rejection_reason = '$rejection_reason'
                    WHERE id = $land_id";

            if(mysqli_query($conn, $sql)) {
                // Log history
                mysqli_query($conn, "
                    INSERT INTO land_history (land_id, event_type, event_description, performed_by, performed_by_role)
                    VALUES ($land_id, 'village_rejected', '$rejection_reason', $user_id, '$user_role')
                ");

                // Send notification to owner
                $title = mysqli_real_escape_string($conn, "Land Rejected - Ardhi Imekataliwa");
                $msg = mysqli_real_escape_string($conn, "Your land '{$land['land_name']}' has been rejected. Reason: $rejection_reason");
                mysqli_query($conn, "
                    INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id)
                    VALUES ({$land['user_id']}, 'village_rejected', '$title', '$msg', $land_id)
                ");

                $message = "Land has been rejected.";
                header("Location: pending_lands?rejected=1");
                exit;
            } else {
                $error = "Failed to reject land: " . mysqli_error($conn);
            }
        }
    }
    elseif($action === 'request_survey') {
        // Move to pending survey status
        $sql = "UPDATE lands SET status = 'pending_survey' WHERE id = $land_id";

        if(mysqli_query($conn, $sql)) {
            mysqli_query($conn, "
                INSERT INTO land_history (land_id, event_type, event_description, performed_by, performed_by_role)
                VALUES ($land_id, 'status_changed', 'Survey requested by village authority', $user_id, '$user_role')
            ");

            $message = "Survey request submitted. A surveyor will be assigned.";
        }
    }
}

// Calculate 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);
}

// Count confirmations
$confirmed_count = 0;
$disputed_count = 0;
foreach($neighbors as $n) {
    if($n['confirmation_status'] === 'confirmed') $confirmed_count++;
    if($n['confirmation_status'] === 'disputed') $disputed_count++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Land - <?php echo htmlspecialchars($land['land_name']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .page-header h1 {
            font-size: 24px;
            font-weight: 700;
            color: #1a1d21;
            margin: 0;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background: #f0f2f5;
            border-radius: 10px;
            color: #6c757d;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: #e2e6ea;
            color: #1a1d21;
        }

        .content-grid {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 24px;
        }

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

        .card {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            border: none;
            margin-bottom: 24px;
        }

        .card-header {
            padding: 20px 24px;
            border-bottom: 1px solid #f0f2f5;
            background: transparent;
        }

        .card-header h3 {
            font-size: 16px;
            font-weight: 600;
            color: #1a1d21;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-header h3 i {
            color: #11998e;
        }

        .card-body {
            padding: 24px;
        }

        /* Map */
        #landMap {
            height: 400px;
            border-radius: 12px;
            z-index: 1;
        }

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

        .info-item {
            padding: 16px;
            background: #f8f9fa;
            border-radius: 12px;
        }

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

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

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

        /* Status Badge */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border-radius: 25px;
            font-size: 13px;
            font-weight: 600;
        }

        .status-pending_village {
            background: #cce5ff;
            color: #004085;
        }

        .status-neighbor_verified {
            background: #d1ecf1;
            color: #0c5460;
        }

        .status-village_verified {
            background: #d4edda;
            color: #155724;
        }

        /* Neighbor List */
        .neighbor-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .neighbor-item {
            display: flex;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f0f2f5;
        }

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

        .neighbor-direction {
            width: 80px;
            font-size: 12px;
            font-weight: 600;
            color: #6c757d;
            text-transform: uppercase;
        }

        .neighbor-info {
            flex: 1;
        }

        .neighbor-name {
            font-weight: 600;
            color: #1a1d21;
        }

        .neighbor-phone {
            font-size: 12px;
            color: #6c757d;
        }

        .neighbor-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .neighbor-status.confirmed {
            background: #d4edda;
            color: #155724;
        }

        .neighbor-status.pending {
            background: #fff3cd;
            color: #856404;
        }

        .neighbor-status.disputed {
            background: #f8d7da;
            color: #721c24;
        }

        /* Enhanced Neighbor List */
        .neighbor-list-enhanced {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .neighbor-card {
            background: #f8fafc;
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid #e2e8f0;
        }

        .neighbor-card-header {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 14px 16px;
            background: white;
        }

        .neighbor-direction-badge {
            width: 44px;
            height: 44px;
            border-radius: 10px;
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 14px;
        }

        .neighbor-main-info {
            flex: 1;
        }

        .neighbor-main-info h5 {
            font-size: 15px;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 4px;
        }

        .neighbor-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            font-size: 12px;
            color: #64748b;
        }

        .auto-detected {
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 10px;
        }

        .neighbor-status-badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .neighbor-status-badge.status-confirmed { background: #d1fae5; color: #059669; }
        .neighbor-status-badge.status-pending { background: #fef3c7; color: #d97706; }
        .neighbor-status-badge.status-disputed { background: #fee2e2; color: #dc2626; }
        .neighbor-status-badge.status-expired { background: #e2e8f0; color: #64748b; }

        .neighbor-card-details {
            padding: 14px 16px;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
        }

        .detail-row {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 0;
            border-bottom: 1px solid #e2e8f0;
        }

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

        .detail-label {
            font-size: 13px;
            color: #64748b;
            min-width: 120px;
        }

        .detail-value {
            font-weight: 500;
            color: #1e293b;
        }

        .id-type-badge, .method-badge {
            background: #e2e8f0;
            color: #475569;
            padding: 2px 8px;
            border-radius: 6px;
            font-size: 11px;
        }

        .view-doc-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
            border-radius: 8px;
            font-size: 12px;
            text-decoration: none;
            transition: all 0.3s;
        }

        .view-doc-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
            color: white;
            text-decoration: none;
        }

        .witness-info {
            padding: 10px;
            background: #eff6ff;
            border-radius: 8px;
            margin-top: 8px;
            font-size: 13px;
        }

        .dispute-details {
            margin-top: 12px;
            padding: 12px;
            background: #fef2f2;
            border-radius: 8px;
            border-left: 3px solid #ef4444;
        }

        .dispute-header {
            font-weight: 600;
            color: #dc2626;
            margin-bottom: 8px;
        }

        .dispute-details p {
            margin: 4px 0;
            font-size: 13px;
            color: #1e293b;
        }

        .neighbor-pending-info {
            padding: 10px 16px;
            background: #fefce8;
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #854d0e;
        }

        .confirmation-code {
            font-family: monospace;
            font-weight: 600;
        }

        /* History Timeline */
        .history-timeline {
            position: relative;
            padding-left: 30px;
        }

        .history-timeline::before {
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e9ecef;
        }

        .history-item {
            position: relative;
            padding-bottom: 20px;
        }

        .history-item:last-child {
            padding-bottom: 0;
        }

        .history-dot {
            position: absolute;
            left: -25px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #11998e;
            border: 2px solid #fff;
            box-shadow: 0 0 0 2px #11998e;
        }

        .history-date {
            font-size: 12px;
            color: #6c757d;
            margin-bottom: 4px;
        }

        .history-event {
            font-weight: 600;
            color: #1a1d21;
        }

        .history-desc {
            font-size: 13px;
            color: #6c757d;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }

        .btn-approve {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 14px 24px;
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            border: none;
            border-radius: 12px;
            color: #fff;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-approve:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(17, 153, 142, 0.3);
        }

        .btn-reject {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 14px 24px;
            background: #f8d7da;
            border: none;
            border-radius: 12px;
            color: #721c24;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-reject:hover {
            background: #f5c6cb;
        }

        .btn-survey {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 14px 24px;
            background: #e2d5f1;
            border: none;
            border-radius: 12px;
            color: #5a3d8a;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 12px;
        }

        .btn-survey:hover {
            background: #d4c4e8;
        }

        /* Alert */
        .alert {
            border-radius: 12px;
            border: none;
            padding: 16px 20px;
        }

        /* Modal */
        .modal-content {
            border-radius: 16px;
            border: none;
        }

        .modal-header {
            border-bottom: 1px solid #f0f2f5;
            padding: 20px 24px;
        }

        .modal-body {
            padding: 24px;
        }

        .modal-footer {
            border-top: 1px solid #f0f2f5;
            padding: 16px 24px;
        }

        /* Verification Summary */
        .verification-summary {
            display: flex;
            gap: 16px;
            margin-bottom: 20px;
        }

        .verify-stat {
            flex: 1;
            padding: 16px;
            background: #f8f9fa;
            border-radius: 12px;
            text-align: center;
        }

        .verify-stat.success {
            background: #d4edda;
        }

        .verify-stat.warning {
            background: #fff3cd;
        }

        .verify-stat.danger {
            background: #f8d7da;
        }

        .verify-stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #1a1d21;
        }

        .verify-stat-label {
            font-size: 12px;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <!-- Page Header -->
        <div class="page-header">
            <div>
                <a href="pending_lands" class="back-btn">
                    <i class="fas fa-arrow-left"></i> Back to Pending
                </a>
                <h1 style="margin-top: 16px;">Verify Land Registration</h1>
            </div>
            <span class="status-badge status-<?php echo $land['status']; ?>">
                <i class="fas fa-info-circle"></i>
                <?php echo ucfirst(str_replace('_', ' ', $land['status'])); ?>
            </span>
        </div>

        <?php if($message): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle mr-2"></i> <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <?php if($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <div class="content-grid">
            <!-- Left Column - Map & Details -->
            <div>
                <!-- Map Card -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-map"></i> Land Boundary Map / Ramani ya Mpaka</h3>
                    </div>
                    <div class="card-body">
                        <div id="landMap"></div>
                    </div>
                </div>

                <!-- Land Details -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-info-circle"></i> Land Information / Taarifa za Ardhi</h3>
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <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">Land Size</div>
                                <div class="info-value large">
                                    <?php echo number_format($land['total_area'], 2); ?>
                                    <small><?php echo strtoupper($land['area_unit']); ?></small>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Owner Name</div>
                                <div class="info-value"><?php echo htmlspecialchars($land['owner_name']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Owner Phone</div>
                                <div class="info-value"><?php echo htmlspecialchars($land['owner_phone']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Village</div>
                                <div class="info-value"><?php echo htmlspecialchars($land['village_name'] ?? 'N/A'); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">District</div>
                                <div class="info-value"><?php echo htmlspecialchars($land['district_name'] ?? 'N/A'); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Registration Date</div>
                                <div class="info-value"><?php echo date('M j, Y', strtotime($land['created_at'])); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">GPS Points</div>
                                <div class="info-value"><?php echo count($beacon_points); ?> boundary points</div>
                            </div>
                        </div>

                        <?php if($land['description']): ?>
                        <div class="info-item mt-3">
                            <div class="info-label">Description</div>
                            <div class="info-value"><?php echo nl2br(htmlspecialchars($land['description'])); ?></div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- History Timeline -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-history"></i> Land History / Historia ya Ardhi</h3>
                    </div>
                    <div class="card-body">
                        <?php if(count($history) > 0): ?>
                        <div class="history-timeline">
                            <?php foreach($history as $event): ?>
                            <div class="history-item">
                                <div class="history-dot"></div>
                                <div class="history-date">
                                    <?php echo date('M j, Y - H:i', strtotime($event['created_at'])); ?>
                                </div>
                                <div class="history-event">
                                    <?php echo ucfirst(str_replace('_', ' ', $event['event_type'])); ?>
                                </div>
                                <div class="history-desc">
                                    <?php echo htmlspecialchars($event['event_description']); ?>
                                    <?php if($event['performed_by_name']): ?>
                                    <br><small>By: <?php echo htmlspecialchars($event['performed_by_name']); ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <p class="text-muted">No history recorded yet.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Right Column - Verification Panel -->
            <div>
                <!-- Verification Summary -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-check-double"></i> Verification Status</h3>
                    </div>
                    <div class="card-body">
                        <div class="verification-summary">
                            <div class="verify-stat success">
                                <div class="verify-stat-value"><?php echo $confirmed_count; ?></div>
                                <div class="verify-stat-label">Confirmed</div>
                            </div>
                            <div class="verify-stat warning">
                                <div class="verify-stat-value"><?php echo count($neighbors) - $confirmed_count - $disputed_count; ?></div>
                                <div class="verify-stat-label">Pending</div>
                            </div>
                            <div class="verify-stat danger">
                                <div class="verify-stat-value"><?php echo $disputed_count; ?></div>
                                <div class="verify-stat-label">Disputed</div>
                            </div>
                        </div>

                        <p class="text-center text-muted mb-0">
                            <i class="fas fa-users"></i>
                            <?php echo $confirmed_count; ?> of <?php echo $land['neighbor_required_count']; ?> required neighbor confirmations
                        </p>
                    </div>
                </div>

                <!-- Neighbor Confirmations -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-users"></i> Neighbor Confirmations</h3>
                    </div>
                    <div class="card-body">
                        <?php if(count($neighbors) > 0): ?>
                        <div class="neighbor-list-enhanced">
                            <?php foreach($neighbors as $neighbor): ?>
                            <?php
                                $directionLabels = [
                                    'north' => 'N', 'south' => 'S', 'east' => 'E', 'west' => 'W',
                                    'northeast' => 'NE', 'northwest' => 'NW', 'southeast' => 'SE', 'southwest' => 'SW'
                                ];
                                $statusClass = '';
                                switch($neighbor['confirmation_status']) {
                                    case 'confirmed': $statusClass = 'status-confirmed'; break;
                                    case 'disputed': $statusClass = 'status-disputed'; break;
                                    case 'no_response': $statusClass = 'status-expired'; break;
                                    default: $statusClass = 'status-pending';
                                }
                            ?>
                            <div class="neighbor-card">
                                <div class="neighbor-card-header">
                                    <div class="neighbor-direction-badge">
                                        <?php echo $directionLabels[$neighbor['neighbor_direction']] ?? 'N'; ?>
                                    </div>
                                    <div class="neighbor-main-info">
                                        <h5><?php echo htmlspecialchars($neighbor['neighbor_name_user'] ?? $neighbor['neighbor_name'] ?? 'Unknown'); ?></h5>
                                        <div class="neighbor-meta">
                                            <?php if($neighbor['neighbor_phone']): ?>
                                            <span><i class="fas fa-phone"></i> <?php echo htmlspecialchars($neighbor['neighbor_phone']); ?></span>
                                            <?php endif; ?>
                                            <?php if(isset($neighbor['detection_method']) && $neighbor['detection_method'] == 'auto'): ?>
                                            <span class="auto-detected"><i class="fas fa-robot"></i> Auto-detected</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <span class="neighbor-status-badge <?php echo $statusClass; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $neighbor['confirmation_status'])); ?>
                                    </span>
                                </div>

                                <?php if($neighbor['confirmation_status'] == 'confirmed' || $neighbor['confirmation_status'] == 'disputed'): ?>
                                <div class="neighbor-card-details">
                                    <!-- ID Information -->
                                    <?php if(isset($neighbor['neighbor_national_id']) && $neighbor['neighbor_national_id']): ?>
                                    <div class="detail-row">
                                        <span class="detail-label"><i class="fas fa-id-card"></i> National ID:</span>
                                        <span class="detail-value"><?php echo htmlspecialchars($neighbor['neighbor_national_id']); ?></span>
                                        <?php if(isset($neighbor['neighbor_id_type'])): ?>
                                        <span class="id-type-badge"><?php echo ucfirst(str_replace('_', ' ', $neighbor['neighbor_id_type'])); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>

                                    <!-- ID Document -->
                                    <?php if(isset($neighbor['neighbor_id_document']) && $neighbor['neighbor_id_document']): ?>
                                    <div class="detail-row">
                                        <span class="detail-label"><i class="fas fa-file-image"></i> ID Document:</span>
                                        <a href="../<?php echo htmlspecialchars($neighbor['neighbor_id_document']); ?>" target="_blank" class="view-doc-btn">
                                            <i class="fas fa-eye"></i> View Document
                                        </a>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Confirmation Document -->
                                    <?php if(isset($neighbor['confirmation_document']) && $neighbor['confirmation_document']): ?>
                                    <div class="detail-row">
                                        <span class="detail-label"><i class="fas fa-file-signature"></i> Signed Form:</span>
                                        <a href="../<?php echo htmlspecialchars($neighbor['confirmation_document']); ?>" target="_blank" class="view-doc-btn">
                                            <i class="fas fa-eye"></i> View Document
                                        </a>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Witness Information -->
                                    <?php if(isset($neighbor['witness_name']) && $neighbor['witness_name']): ?>
                                    <div class="witness-info">
                                        <span class="detail-label"><i class="fas fa-user-friends"></i> Witness:</span>
                                        <span><?php echo htmlspecialchars($neighbor['witness_name']); ?></span>
                                        <?php if(isset($neighbor['witness_phone']) && $neighbor['witness_phone']): ?>
                                        <span class="text-muted"> - <?php echo htmlspecialchars($neighbor['witness_phone']); ?></span>
                                        <?php endif; ?>
                                        <?php if(isset($neighbor['witness_national_id']) && $neighbor['witness_national_id']): ?>
                                        <span class="text-muted"> (ID: <?php echo htmlspecialchars($neighbor['witness_national_id']); ?>)</span>
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Confirmation Date -->
                                    <?php if($neighbor['confirmed_at']): ?>
                                    <div class="detail-row">
                                        <span class="detail-label"><i class="fas fa-calendar-check"></i> Confirmed:</span>
                                        <span class="detail-value"><?php echo date('M j, Y g:i A', strtotime($neighbor['confirmed_at'])); ?></span>
                                        <?php if(isset($neighbor['confirmation_method']) && $neighbor['confirmation_method']): ?>
                                        <span class="method-badge">via <?php echo ucfirst($neighbor['confirmation_method']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Dispute Information -->
                                    <?php if($neighbor['confirmation_status'] == 'disputed'): ?>
                                    <div class="dispute-details">
                                        <div class="dispute-header"><i class="fas fa-exclamation-triangle"></i> Dispute Details</div>
                                        <?php if(isset($neighbor['dispute_reason']) && $neighbor['dispute_reason']): ?>
                                        <p><strong>Reason:</strong> <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $neighbor['dispute_reason']))); ?></p>
                                        <?php endif; ?>
                                        <?php if(isset($neighbor['dispute_boundary_description']) && $neighbor['dispute_boundary_description']): ?>
                                        <p><strong>Description:</strong> <?php echo htmlspecialchars($neighbor['dispute_boundary_description']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php elseif($neighbor['confirmation_status'] == 'pending'): ?>
                                <div class="neighbor-pending-info">
                                    <span class="confirmation-code">Code: <?php echo $neighbor['confirmation_code'] ?? 'N/A'; ?></span>
                                    <?php if(isset($neighbor['expires_at'])): ?>
                                    <span class="expiry-info">Expires: <?php echo date('M j, Y', strtotime($neighbor['expires_at'])); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <p class="text-muted text-center">
                            <i class="fas fa-info-circle"></i> No neighbors added yet
                        </p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Action Panel -->
                <?php if($land['status'] === 'pending_village' || $land['status'] === 'neighbor_verified'): ?>
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-gavel"></i> Take Action / Chukua Hatua</h3>
                    </div>
                    <div class="card-body">
                        <?php if($disputed_count > 0): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>Warning:</strong> This land has <?php echo $disputed_count; ?> neighbor dispute(s).
                            Consider investigating before approving.
                        </div>
                        <?php endif; ?>

                        <form method="POST">
                            <div class="action-buttons">
                                <button type="submit" name="action" value="approve" class="btn-approve"
                                        onclick="return confirm('Are you sure you want to APPROVE this land registration?')">
                                    <i class="fas fa-check"></i> Approve / Kubali
                                </button>
                                <button type="button" class="btn-reject" data-toggle="modal" data-target="#rejectModal">
                                    <i class="fas fa-times"></i> Reject / Kataa
                                </button>
                            </div>
                            <button type="submit" name="action" value="request_survey" class="btn-survey">
                                <i class="fas fa-ruler-combined"></i> Request Surveyor Verification
                            </button>
                        </form>
                    </div>
                </div>
                <?php elseif($land['status'] === 'village_verified'): ?>
                <div class="card">
                    <div class="card-body text-center">
                        <i class="fas fa-check-circle text-success" style="font-size: 48px;"></i>
                        <h4 class="mt-3">Land Verified</h4>
                        <p class="text-muted">This land has been approved by village authority.</p>
                        <small>Verified on: <?php echo date('M j, Y', strtotime($land['village_verified_at'])); ?></small>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- Reject Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-times-circle text-danger"></i> Reject Land Registration
                    </h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <div class="form-group">
                            <label><strong>Reason for Rejection / Sababu ya Kukataa</strong></label>
                            <textarea name="rejection_reason" class="form-control" rows="4"
                                      placeholder="Enter the reason for rejecting this land registration..."
                                      required></textarea>
                            <small class="form-text text-muted">
                                This reason will be sent to the land owner.
                            </small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" name="action" value="reject" class="btn btn-danger">
                            <i class="fas fa-times"></i> Confirm Rejection
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        // Initialize map
        var map = L.map('landMap').setView([<?php echo $center_lat; ?>, <?php echo $center_lng; ?>], 17);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'
        }).addTo(map);

        // Draw polygon
        var beaconPoints = <?php echo json_encode($beacon_points); ?>;
        if (beaconPoints.length > 0) {
            var latlngs = beaconPoints.map(function(p) {
                return [parseFloat(p.latitude), parseFloat(p.longitude)];
            });

            var polygon = L.polygon(latlngs, {
                color: '#11998e',
                fillColor: '#38ef7d',
                fillOpacity: 0.3,
                weight: 3
            }).addTo(map);

            // Add markers for each point
            beaconPoints.forEach(function(point, index) {
                L.circleMarker([point.latitude, point.longitude], {
                    radius: 8,
                    fillColor: '#ff5722',
                    color: '#fff',
                    weight: 2,
                    fillOpacity: 1
                }).addTo(map)
                .bindPopup('<strong>Point ' + (index + 1) + '</strong><br>' +
                          'Lat: ' + point.latitude + '<br>' +
                          'Lng: ' + point.longitude);
            });

            map.fitBounds(polygon.getBounds(), { padding: [20, 20] });
        }
    </script>
</body>
</html>
