<?php
/**
 * Client Dashboard
 * Dashboard for clients to view their lands
 */

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

initSecureSession();

// Require client authentication
if(!isAuthenticated() || !validateSession() || !isset($_SESSION['is_client'])) {
    header('Location: login');
    exit;
}

$client_id = $_SESSION['user_id'];
$client_name = $_SESSION['full_name'];
$broker_name = $_SESSION['broker_name'] ?? '';

// Get client's lands
$lands_sql = "SELECT l.*,
              (SELECT COUNT(*) FROM beacon_points WHERE land_id = l.id) as beacon_count
              FROM lands l
              WHERE l.client_id = $client_id
              ORDER BY l.created_at DESC";
$lands_result = mysqli_query($conn, $lands_sql);
$lands_count = mysqli_num_rows($lands_result);

// Get total area
$area_result = mysqli_query($conn, "SELECT SUM(total_area) as total FROM lands WHERE client_id = $client_id AND area_unit = 'sqm'");
$total_area = mysqli_fetch_assoc($area_result)['total'] ?? 0;

// Get payment status
$current_year = date('Y');
$payment_result = mysqli_query($conn, "SELECT * FROM client_payments WHERE client_id = $client_id AND payment_year = $current_year AND status = 'confirmed' LIMIT 1");
$is_paid = mysqli_num_rows($payment_result) > 0;

$page_title = 'My Dashboard';
$current_page = 'client_dashboard';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Land Secure App</title>
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#1a3a6e">
    <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 rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        :root {
            --primary: #1a3a6e;
            --primary-light: #2d5a9e;
            --secondary: #2d5a3d;
            --secondary-light: #3d7a52;
            --accent: #e67e22;
            --danger: #dc3545;
            --success: #28a745;
            --warning: #ffc107;
            --info: #0ea5e9;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --gray-400: #94a3b8;
            --gray-500: #64748b;
            --gray-600: #475569;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --gray-900: #0f172a;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 25px -5px rgba(0,0,0,0.1);
            --shadow-xl: 0 25px 50px -12px rgba(0,0,0,0.15);
            --radius: 12px;
            --radius-lg: 16px;
            --radius-xl: 24px;
        }

        body {
            background: var(--gray-100);
            min-height: 100vh;
        }

        /* Header */
        .app-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            padding: 20px 24px;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .header-brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-brand-icon {
            width: 40px;
            height: 40px;
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .header-brand h1 {
            font-size: 18px;
            font-weight: 600;
        }

        .header-brand span {
            font-size: 12px;
            opacity: 0.8;
        }

        .header-user {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }

        .user-info {
            text-align: right;
        }

        .user-name {
            font-weight: 600;
            font-size: 14px;
        }

        .user-role {
            font-size: 11px;
            opacity: 0.8;
        }

        .btn-logout {
            background: rgba(255,255,255,0.15);
            border: none;
            color: white;
            padding: 10px 16px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: background 0.2s;
            text-decoration: none;
        }

        .btn-logout:hover {
            background: rgba(255,255,255,0.25);
        }

        /* Main Content */
        .main-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 24px;
        }

        /* Welcome Section */
        .welcome-section {
            background: white;
            border-radius: var(--radius-lg);
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: var(--shadow);
        }

        .welcome-section h2 {
            font-size: 24px;
            color: var(--gray-800);
            margin-bottom: 8px;
        }

        .welcome-section p {
            color: var(--gray-500);
            font-size: 14px;
        }

        .broker-info {
            margin-top: 12px;
            padding: 12px 16px;
            background: var(--gray-50);
            border-radius: var(--radius);
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: var(--gray-600);
        }

        .broker-info i {
            color: var(--primary);
        }

        /* Stats Row */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: white;
            border-radius: var(--radius-lg);
            padding: 20px;
            box-shadow: var(--shadow);
            display: flex;
            align-items: center;
            gap: 16px;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .stat-icon {
            width: 56px;
            height: 56px;
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }

        .stat-icon.primary { background: linear-gradient(135deg, var(--primary), var(--primary-light)); }
        .stat-icon.success { background: linear-gradient(135deg, var(--secondary), var(--secondary-light)); }
        .stat-icon.warning { background: linear-gradient(135deg, #f59e0b, #fbbf24); }
        .stat-icon.info { background: linear-gradient(135deg, var(--info), #38bdf8); }

        .stat-content h3 {
            font-size: 28px;
            font-weight: 700;
            color: var(--gray-800);
            line-height: 1;
            margin-bottom: 4px;
        }

        .stat-content p {
            font-size: 13px;
            color: var(--gray-500);
            margin: 0;
        }

        /* Payment Status */
        .payment-status {
            background: white;
            border-radius: var(--radius-lg);
            padding: 20px;
            margin-bottom: 24px;
            box-shadow: var(--shadow);
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 16px;
        }

        .payment-info {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .payment-icon {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .payment-icon.paid {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success);
        }

        .payment-icon.unpaid {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger);
        }

        .payment-text h4 {
            font-size: 16px;
            color: var(--gray-800);
            margin-bottom: 4px;
        }

        .payment-text p {
            font-size: 13px;
            color: var(--gray-500);
            margin: 0;
        }

        .badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .badge-success {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success);
        }

        .badge-danger {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger);
        }

        /* Section Title */
        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-800);
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-title i {
            color: var(--primary);
        }

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

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

        /* Land Card */
        .land-card {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow);
            overflow: hidden;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .land-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .land-card-map {
            height: 180px;
            background: var(--gray-200);
            position: relative;
        }

        .land-card-body {
            padding: 20px;
        }

        .land-name {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-800);
            margin-bottom: 8px;
        }

        .land-location {
            font-size: 13px;
            color: var(--gray-500);
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 16px;
        }

        .land-stats {
            display: flex;
            gap: 20px;
            padding-top: 16px;
            border-top: 1px solid var(--gray-100);
        }

        .land-stat {
            text-align: center;
        }

        .land-stat-value {
            font-size: 18px;
            font-weight: 700;
            color: var(--gray-800);
        }

        .land-stat-label {
            font-size: 11px;
            color: var(--gray-500);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .land-card-footer {
            padding: 16px 20px;
            background: var(--gray-50);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .land-status {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .land-status.active {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success);
        }

        .land-status.verified {
            background: rgba(14, 165, 233, 0.1);
            color: var(--info);
        }

        .land-status.disputed {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger);
        }

        .btn-view {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .btn-view:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(26, 58, 110, 0.3);
        }

        /* Empty State */
        .empty-state {
            background: white;
            border-radius: var(--radius-lg);
            padding: 60px 40px;
            text-align: center;
            box-shadow: var(--shadow);
        }

        .empty-state-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: var(--gray-100);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
        }

        .empty-state-icon i {
            font-size: 36px;
            color: var(--gray-400);
        }

        .empty-state h3 {
            font-size: 20px;
            font-weight: 600;
            color: var(--gray-800);
            margin-bottom: 8px;
        }

        .empty-state p {
            font-size: 14px;
            color: var(--gray-500);
        }

        /* Footer */
        .app-footer {
            text-align: center;
            padding: 24px;
            color: var(--gray-500);
            font-size: 13px;
        }

        @media (max-width: 768px) {
            .app-header {
                flex-direction: column;
                gap: 16px;
                text-align: center;
            }

            .header-user {
                width: 100%;
                justify-content: center;
            }

            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }

            .payment-status {
                flex-direction: column;
                text-align: center;
            }

            .payment-info {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="app-header">
        <div class="header-brand">
            <div class="header-brand-icon">
                <i class="fas fa-map-marked-alt"></i>
            </div>
            <div>
                <h1>Land Secure</h1>
                <span>Client Portal</span>
            </div>
        </div>
        <div class="header-user">
            <div class="user-avatar">
                <?php echo strtoupper(substr($client_name, 0, 1)); ?>
            </div>
            <div class="user-info">
                <div class="user-name"><?php echo htmlspecialchars($client_name); ?></div>
                <div class="user-role">Client Account</div>
            </div>
            <a href="logout" class="btn-logout">
                <i class="fas fa-sign-out-alt"></i>
                Logout
            </a>
        </div>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Welcome Section -->
        <div class="welcome-section">
            <h2>Welcome back, <?php echo htmlspecialchars(explode(' ', $client_name)[0]); ?>!</h2>
            <p>View and manage your registered land parcels</p>
            <?php if($broker_name): ?>
            <div class="broker-info">
                <i class="fas fa-user-tie"></i>
                Your Broker: <strong><?php echo htmlspecialchars($broker_name); ?></strong>
            </div>
            <?php endif; ?>
        </div>

        <!-- Stats Row -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon primary">
                    <i class="fas fa-map"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo number_format($lands_count); ?></h3>
                    <p>Registered Lands</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon success">
                    <i class="fas fa-ruler-combined"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo number_format($total_area, 0); ?></h3>
                    <p>Total Area (sqm)</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon <?php echo $is_paid ? 'info' : 'warning'; ?>">
                    <i class="fas fa-<?php echo $is_paid ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo $is_paid ? 'Paid' : 'Unpaid'; ?></h3>
                    <p><?php echo $current_year; ?> Status</p>
                </div>
            </div>
        </div>

        <!-- Payment Status -->
        <div class="payment-status">
            <div class="payment-info">
                <div class="payment-icon <?php echo $is_paid ? 'paid' : 'unpaid'; ?>">
                    <i class="fas fa-<?php echo $is_paid ? 'check' : 'clock'; ?>"></i>
                </div>
                <div class="payment-text">
                    <h4><?php echo $is_paid ? 'Payment Up to Date' : 'Payment Required'; ?></h4>
                    <p><?php echo $is_paid ? 'Your ' . $current_year . ' subscription is active' : 'Please contact your broker for ' . $current_year . ' payment'; ?></p>
                </div>
            </div>
            <span class="badge <?php echo $is_paid ? 'badge-success' : 'badge-danger'; ?>">
                <?php echo $is_paid ? 'Active' : 'Pending Payment'; ?>
            </span>
        </div>

        <!-- My Lands Section -->
        <h3 class="section-title">
            <i class="fas fa-layer-group"></i>
            My Land Parcels
        </h3>

        <?php if($lands_count == 0): ?>
        <div class="empty-state">
            <div class="empty-state-icon">
                <i class="fas fa-map"></i>
            </div>
            <h3>No Lands Registered Yet</h3>
            <p>Your broker will register your land parcels. Please contact them for assistance.</p>
        </div>
        <?php else: ?>
        <div class="lands-grid">
            <?php while($land = mysqli_fetch_assoc($lands_result)): ?>
            <div class="land-card">
                <div class="land-card-map" id="map-<?php echo $land['id']; ?>"></div>
                <div class="land-card-body">
                    <h4 class="land-name"><?php echo htmlspecialchars($land['land_name']); ?></h4>
                    <div class="land-location">
                        <i class="fas fa-map-marker-alt"></i>
                        <?php echo htmlspecialchars($land['location_address'] ?: 'Location not specified'); ?>
                    </div>
                    <div class="land-stats">
                        <div class="land-stat">
                            <div class="land-stat-value"><?php echo number_format($land['total_area'], 2); ?></div>
                            <div class="land-stat-label"><?php echo strtoupper($land['area_unit']); ?></div>
                        </div>
                        <div class="land-stat">
                            <div class="land-stat-value"><?php echo $land['beacon_count']; ?></div>
                            <div class="land-stat-label">Beacons</div>
                        </div>
                        <div class="land-stat">
                            <div class="land-stat-value"><?php echo date('M Y', strtotime($land['created_at'])); ?></div>
                            <div class="land-stat-label">Registered</div>
                        </div>
                    </div>
                </div>
                <div class="land-card-footer">
                    <span class="land-status <?php echo $land['status']; ?>">
                        <i class="fas fa-<?php echo $land['status'] == 'verified' ? 'shield-alt' : ($land['status'] == 'disputed' ? 'exclamation-triangle' : 'check-circle'); ?>"></i>
                        <?php echo ucfirst($land['status']); ?>
                    </span>
                    <a href="<?php echo url('land/' . $land['id']); ?>" class="btn-view">
                        <i class="fas fa-eye"></i>
                        View Details
                    </a>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="app-footer">
        <p>&copy; <?php echo date('Y'); ?> Land Secure App. All rights reserved.</p>
    </footer>

    <script>
        // Initialize maps for each land
        <?php
        mysqli_data_seek($lands_result, 0);
        while($land = mysqli_fetch_assoc($lands_result)):
            // Get beacon points for this land
            $beacons = mysqli_query($conn, "SELECT latitude, longitude FROM beacon_points WHERE land_id = {$land['id']} ORDER BY point_order");
            $points = [];
            while($b = mysqli_fetch_assoc($beacons)) {
                $points[] = [$b['latitude'], $b['longitude']];
            }
        ?>
        (function() {
            var points = <?php echo json_encode($points); ?>;
            if (points.length > 0) {
                var map = L.map('map-<?php echo $land['id']; ?>', {
                    zoomControl: false,
                    attributionControl: false,
                    dragging: false,
                    scrollWheelZoom: false
                });

                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

                var polygon = L.polygon(points, {
                    color: '#1a3a6e',
                    fillColor: '#2d5a9e',
                    fillOpacity: 0.3,
                    weight: 2
                }).addTo(map);

                map.fitBounds(polygon.getBounds(), { padding: [20, 20] });
            } else {
                document.getElementById('map-<?php echo $land['id']; ?>').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;"><i class="fas fa-map" style="font-size:32px;"></i></div>';
            }
        })();
        <?php endwhile; ?>
    </script>
</body>
</html>
