<?php
/**
 * Lands List
 * Display all lands for the user
 */

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

initSecureSession();

// Require authentication
if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';

// Payment check for regular users
$payment_required = false;
$payment_message = '';

if($user_role == 'user') {
    // Check if user has any lands
    $lands_check = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM lands WHERE user_id = $user_id"));

    if($lands_check['count'] > 0) {
        // User has lands, check payment status
        $current_year = date('Y');

        // Get user's registration/subscription date
        $user_info = mysqli_fetch_assoc(mysqli_query($conn, "SELECT subscription_start_date, created_at FROM users WHERE id = $user_id"));
        $subscription_date = $user_info['subscription_start_date'] ?: date('Y-m-d', strtotime($user_info['created_at']));
        $subscription_month_day = date('m-d', strtotime($subscription_date));
        $current_month_day = date('m-d');

        // Determine which year's payment is required
        // If current date is before subscription anniversary, check last year's payment
        // If current date is on or after anniversary, check current year's payment
        if($current_month_day >= $subscription_month_day) {
            $required_payment_year = $current_year;
        } else {
            $required_payment_year = $current_year - 1;
        }

        // Check if payment exists for required year
        $payment_check = mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT id FROM user_payments
             WHERE user_id = $user_id
             AND payment_year = $required_payment_year
             AND status = 'confirmed'"
        ));

        if(!$payment_check) {
            $payment_required = true;
            $next_payment_date = date('d M Y', strtotime($required_payment_year . '-' . $subscription_month_day));
            $payment_message = "Your subscription payment for year $required_payment_year is required. Your payment was due on $next_payment_date. Please contact the administrator to make your payment.";
        }
    }
}

// Filter by client (for brokers/admins)
$filter_client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
$filter_client = null;

// Handle delete
if(isset($_GET['delete'])) {
    $land_id = intval($_GET['delete']);

    // Simple ownership check - user can only delete their own lands
    $delete_check = "user_id = $user_id";

    // Admin can delete any land
    if($user_role == 'admin') {
        $delete_check = "1=1";
    }

    // First delete related beacon_points
    mysqli_query($conn, "DELETE FROM beacon_points WHERE land_id = $land_id");

    // Then delete the land
    mysqli_query($conn, "DELETE FROM lands WHERE id = $land_id AND ($delete_check)");

    header('Location: lands?success=Land deleted successfully' . ($filter_client_id ? '&client_id=' . $filter_client_id : ''));
    exit;
}

// Build query based on role and filters
$where = "l.user_id = $user_id";
if($user_role == 'admin') {
    $where = "1=1"; // Admin sees all by default
}

// Check if clients table exists
$clientsTableExists = false;
$checkClients = mysqli_query($conn, "SHOW TABLES LIKE 'clients'");
if($checkClients && mysqli_num_rows($checkClients) > 0) {
    $clientsTableExists = true;
}

// Filter by specific client (only if clients table exists)
if($filter_client_id > 0 && $clientsTableExists) {
    $where .= " AND l.client_id = $filter_client_id";
    // Get client info
    $filter_client = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM clients WHERE id = $filter_client_id"));
}

// Get all lands - simplified query for compatibility
if($clientsTableExists) {
    $lands = mysqli_query($conn, "SELECT l.*, COUNT(bp.id) as point_count, c.full_name as client_name, c.phone as client_phone
        FROM lands l
        LEFT JOIN beacon_points bp ON l.id = bp.land_id
        LEFT JOIN clients c ON l.client_id = c.id
        WHERE $where
        GROUP BY l.id
        ORDER BY l.created_at DESC");
} else {
    $lands = mysqli_query($conn, "SELECT l.*, COUNT(bp.id) as point_count, NULL as client_name, NULL as client_phone
        FROM lands l
        LEFT JOIN beacon_points bp ON l.id = bp.land_id
        WHERE $where
        GROUP BY l.id
        ORDER BY l.created_at DESC");
}

$lands_count = mysqli_num_rows($lands);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#1a1f2e">
    <title>My Lands - Land Secure</title>
    <link rel="manifest" href="manifest.json">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&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">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <?php if($payment_required): ?>
        <!-- Payment Required Notice -->
        <div class="payment-required-container">
            <div class="payment-required-card">
                <div class="payment-icon">
                    <i class="fas fa-lock"></i>
                </div>
                <h2>Subscription Payment Required</h2>
                <p class="payment-message"><?php echo $payment_message; ?></p>
                <div class="payment-info">
                    <div class="info-row">
                        <i class="fas fa-map-marked-alt"></i>
                        <span>You have <strong><?php echo $lands_check['count']; ?> land(s)</strong> registered</span>
                    </div>
                    <div class="info-row">
                        <i class="fas fa-calendar-alt"></i>
                        <span>Payment Year: <strong><?php echo $required_payment_year; ?></strong></span>
                    </div>
                    <div class="info-row">
                        <i class="fas fa-money-bill-wave"></i>
                        <span>Access will be restored after payment confirmation</span>
                    </div>
                </div>
                <div class="payment-actions">
                    <a href="<?php echo url('user-payments'); ?>" class="btn-payment">
                        <i class="fas fa-receipt"></i> View Payment History
                    </a>
                    <a href="<?php echo url('dashboard'); ?>" class="btn-back">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                </div>
            </div>
        </div>
        <?php else: ?>
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1>
                        <i class="fas fa-map"></i>
                        <?php if($filter_client): ?>
                        Lands for <?php echo htmlspecialchars($filter_client['full_name']); ?>
                        <?php else: ?>
                        My Lands
                        <?php endif; ?>
                    </h1>
                    <p>
                        <?php if($filter_client): ?>
                        Client: <?php echo htmlspecialchars($filter_client['phone']); ?>
                        <?php else: ?>
                        Manage and view all your registered land parcels
                        <?php endif; ?>
                    </p>
                </div>
                <div class="header-actions">
                    <?php if($filter_client): ?>
                    <a href="<?php echo url('lands'); ?>" class="btn-action secondary">
                        <i class="fas fa-times"></i>
                        <span>Clear Filter</span>
                    </a>
                    <a href="<?php echo url('add-land?client_id=' . $filter_client_id); ?>" class="btn-action primary">
                        <i class="fas fa-plus"></i>
                        <span>Add Land for Client</span>
                    </a>
                    <?php else: ?>
                    <a href="<?php echo url('add-land'); ?>" class="btn-action primary">
                        <i class="fas fa-plus"></i>
                        <span>Add New Land</span>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if(isset($_GET['success'])): ?>
        <div class="alert-card success">
            <i class="fas fa-check-circle"></i>
            <span><?php echo htmlspecialchars($_GET['success']); ?></span>
            <button onclick="this.parentElement.remove()"><i class="fas fa-times"></i></button>
        </div>
        <?php endif; ?>

        <!-- Stats Summary -->
        <div class="stats-mini">
            <div class="stat-mini-item">
                <i class="fas fa-map-marked-alt"></i>
                <span><?php echo $lands_count; ?> Lands</span>
            </div>
        </div>

        <?php if($lands_count > 0): ?>
        <!-- Lands Grid -->
        <div class="lands-grid">
            <?php while($land = mysqli_fetch_assoc($lands)): ?>
            <div class="land-card">
                <div class="land-card-header">
                    <div class="land-title">
                        <h3><?php echo htmlspecialchars($land['land_name']); ?></h3>
                        <?php if($land['client_name']): ?>
                        <span class="client-badge">
                            <i class="fas fa-user"></i>
                            <?php echo htmlspecialchars($land['client_name']); ?>
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="land-menu">
                        <button class="menu-btn" onclick="toggleMenu(this)">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <div class="menu-dropdown">
                            <a href="<?php echo url('land/' . $land['id']); ?>">
                                <i class="fas fa-eye"></i> View Details
                            </a>
                            <a href="<?php echo url('certificate?id=' . $land['id']); ?>">
                                <i class="fas fa-certificate"></i> View Certificate
                            </a>
                            <a href="<?php echo url('edit-land/' . $land['id']); ?>">
                                <i class="fas fa-edit"></i> Edit Land
                            </a>
                            <a href="<?php echo url('share-land/' . $land['id']); ?>">
                                <i class="fas fa-share-alt"></i> Share
                            </a>
                            <div class="menu-divider"></div>
                            <a href="<?php echo url('lands?delete=' . $land['id']); ?>" class="danger"
                               onclick="return confirm('Are you sure you want to delete this land?')">
                                <i class="fas fa-trash"></i> Delete
                            </a>
                        </div>
                    </div>
                </div>

                <?php if($land['description']): ?>
                <p class="land-description"><?php echo htmlspecialchars(substr($land['description'], 0, 80)); ?>...</p>
                <?php endif; ?>

                <div class="land-info">
                    <div class="info-item">
                        <i class="fas fa-map-marker-alt"></i>
                        <span><?php echo $land['location_address'] ?: 'No address'; ?></span>
                    </div>
                    <div class="info-item">
                        <i class="fas fa-ruler-combined"></i>
                        <span><?php echo number_format($land['total_area'], 2) . ' ' . $land['area_unit']; ?></span>
                    </div>
                    <div class="info-item">
                        <i class="fas fa-map-pin"></i>
                        <span><?php echo $land['point_count']; ?> beacon points</span>
                    </div>
                </div>

                <div class="land-card-footer">
                    <span class="land-date">
                        <i class="fas fa-calendar"></i>
                        <?php echo date('M d, Y', strtotime($land['created_at'])); ?>
                    </span>
                    <?php if($land['share_token']): ?>
                    <span class="shared-badge">
                        <i class="fas fa-share-alt"></i> Shared
                    </span>
                    <?php endif; ?>
                </div>

                <div class="land-card-actions">
                    <a href="<?php echo url('land/' . $land['id']); ?>" class="btn-card primary">
                        <i class="fas fa-eye"></i> View
                    </a>
                    <a href="<?php echo url('certificate?id=' . $land['id']); ?>" class="btn-card certificate">
                        <i class="fas fa-certificate"></i> Certificate
                    </a>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php else: ?>
        <!-- Empty State -->
        <div class="empty-state-card">
            <div class="empty-icon">
                <i class="fas fa-map"></i>
            </div>
            <h3>No Lands Yet</h3>
            <p>Start by adding your first land parcel to track its boundaries and beacon points.</p>
            <a href="<?php echo url('add-land'); ?>" class="btn-action primary">
                <i class="fas fa-plus"></i>
                <span>Add New Land</span>
            </a>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </main>

    <style>
    /* Payment Required Styles */
    .payment-required-container {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 60vh;
        padding: 20px;
    }

    .payment-required-card {
        background: white;
        border-radius: 24px;
        padding: 48px;
        text-align: center;
        max-width: 500px;
        width: 100%;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
    }

    .payment-icon {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 24px;
        font-size: 40px;
        color: white;
        box-shadow: 0 10px 30px rgba(239, 68, 68, 0.3);
    }

    .payment-required-card h2 {
        font-size: 24px;
        font-weight: 700;
        color: #1e293b;
        margin: 0 0 16px;
    }

    .payment-message {
        color: #64748b;
        font-size: 15px;
        line-height: 1.6;
        margin-bottom: 24px;
    }

    .payment-info {
        background: #fef2f2;
        border: 1px solid #fecaca;
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 24px;
    }

    .payment-info .info-row {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 10px 0;
        border-bottom: 1px solid #fecaca;
        color: #991b1b;
        font-size: 14px;
    }

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

    .payment-info .info-row i {
        width: 20px;
        color: #dc2626;
    }

    .payment-actions {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .btn-payment {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 14px 24px;
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        color: white;
        border-radius: 12px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
    }

    .btn-payment:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        color: white;
        text-decoration: none;
    }

    .btn-back {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 14px 24px;
        background: #f1f5f9;
        color: #64748b;
        border-radius: 12px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
    }

    .btn-back:hover {
        background: #e2e8f0;
        color: #475569;
        text-decoration: none;
    }

    /* Page Header */
    .page-header {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;
    }

    .page-title h1 {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
        font-size: 15px;
    }

    .header-actions {
        display: flex;
        gap: 12px;
    }

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

    .btn-action.primary {
        background: white;
        color: #11998e;
    }

    .btn-action.secondary {
        background: rgba(255, 255, 255, 0.2);
        color: white;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
        text-decoration: none;
        color: inherit;
    }

    /* Alert Card */
    .alert-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px 20px;
        border-radius: 12px;
        margin-bottom: 20px;
    }

    .alert-card.success {
        background: rgba(34, 197, 94, 0.1);
        color: #16a34a;
    }

    .alert-card button {
        margin-left: auto;
        background: none;
        border: none;
        color: inherit;
        cursor: pointer;
        opacity: 0.7;
    }

    /* Stats Mini */
    .stats-mini {
        display: flex;
        gap: 20px;
        margin-bottom: 24px;
    }

    .stat-mini-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        background: white;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 500;
        color: #475569;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }

    .stat-mini-item i {
        color: #11998e;
    }

    /* Lands Grid */
    .lands-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
        gap: 24px;
    }

    /* Land Card */
    .land-card {
        background: white;
        border-radius: 20px;
        padding: 24px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
    }

    .land-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.1);
    }

    .land-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;
    }

    .land-title h3 {
        font-size: 18px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 8px 0;
    }

    .client-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 12px;
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        color: white;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }

    .land-menu {
        position: relative;
    }

    .menu-btn {
        width: 36px;
        height: 36px;
        border: none;
        background: #f1f5f9;
        border-radius: 10px;
        color: #64748b;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .menu-btn:hover {
        background: #e2e8f0;
        color: #1e293b;
    }

    .menu-dropdown {
        position: absolute;
        top: 100%;
        right: 0;
        background: white;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
        min-width: 180px;
        padding: 8px;
        z-index: 100;
        display: none;
    }

    .menu-dropdown.active {
        display: block;
    }

    .menu-dropdown a {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 14px;
        border-radius: 8px;
        color: #475569;
        text-decoration: none;
        font-size: 14px;
        transition: all 0.2s ease;
    }

    .menu-dropdown a:hover {
        background: #f1f5f9;
        color: #1e293b;
    }

    .menu-dropdown a.danger {
        color: #dc2626;
    }

    .menu-dropdown a.danger:hover {
        background: rgba(220, 38, 38, 0.1);
    }

    .menu-divider {
        height: 1px;
        background: #f1f5f9;
        margin: 8px 0;
    }

    .land-description {
        font-size: 14px;
        color: #64748b;
        margin-bottom: 16px;
        line-height: 1.5;
    }

    .land-info {
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin-bottom: 16px;
    }

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

    .info-item i {
        width: 16px;
        color: #94a3b8;
    }

    .land-card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 16px;
        border-top: 1px solid #f1f5f9;
        margin-bottom: 16px;
    }

    .land-date {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        color: #94a3b8;
    }

    .shared-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 12px;
        background: rgba(34, 197, 94, 0.1);
        color: #22c55e;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }

    .land-card-actions {
        display: flex;
        gap: 10px;
    }

    .btn-card {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 16px;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 500;
        text-decoration: none;
        transition: all 0.3s ease;
    }

    .btn-card.primary {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        color: white;
    }

    .btn-card.secondary {
        background: #f1f5f9;
        color: #475569;
    }

    .btn-card.certificate {
        background: linear-gradient(135deg, #d4af37 0%, #f5d77a 100%);
        color: #1a3a6e;
    }

    .btn-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        text-decoration: none;
        color: inherit;
    }

    /* Empty State */
    .empty-state-card {
        background: white;
        border-radius: 20px;
        padding: 60px 40px;
        text-align: center;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    }

    .empty-icon {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: linear-gradient(135deg, rgba(17, 153, 142, 0.1) 0%, rgba(56, 239, 125, 0.1) 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 24px;
        font-size: 40px;
        color: #11998e;
    }

    .empty-state-card h3 {
        font-size: 22px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 12px 0;
    }

    .empty-state-card p {
        color: #64748b;
        margin: 0 0 24px 0;
        max-width: 400px;
        margin-left: auto;
        margin-right: auto;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }

        .page-header-content {
            flex-direction: column;
            align-items: flex-start;
        }

        .page-title h1 {
            font-size: 22px;
        }

        .header-actions {
            width: 100%;
            flex-direction: column;
        }

        .btn-action {
            justify-content: center;
        }

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

        .land-card {
            padding: 20px;
        }
    }
    </style>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/offline-storage.js"></script>

    <script>
    // Menu toggle
    function toggleMenu(btn) {
        const dropdown = btn.nextElementSibling;
        const isActive = dropdown.classList.contains('active');

        // Close all other menus
        document.querySelectorAll('.menu-dropdown.active').forEach(menu => {
            menu.classList.remove('active');
        });

        if (!isActive) {
            dropdown.classList.add('active');
        }
    }

    // Close menu when clicking outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.land-menu')) {
            document.querySelectorAll('.menu-dropdown.active').forEach(menu => {
                menu.classList.remove('active');
            });
        }
    });

    // Register Service Worker
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/sw.js');
    }
    </script>
</body>
</html>
