<?php
/**
 * Client Lands - Broker View-Only
 * Shows lands registered by a specific client
 * Broker has view-only access
 */

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

initSecureSession();

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

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

// Only brokers and admins can access
if(!in_array($user_role, ['broker', 'admin'])) {
    header('Location: dashboard?error=Access denied');
    exit;
}

$client_user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if($client_user_id == 0) {
    header('Location: my-clients?error=Invalid client');
    exit;
}

// Verify broker has access to this client
if($user_role == 'broker') {
    $access_check = $conn->prepare("SELECT id FROM users WHERE id = ? AND referred_by_broker = ?");
    $access_check->bind_param("ii", $client_user_id, $user_id);
    $access_check->execute();
    if($access_check->get_result()->num_rows == 0) {
        header('Location: my-clients?error=Access denied');
        exit;
    }
}

// Get client info
$client = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE id = $client_user_id"));
if(!$client) {
    header('Location: my-clients?error=Client not found');
    exit;
}

// Get client's lands
$lands_result = mysqli_query($conn, "SELECT l.*,
    (SELECT COUNT(*) FROM beacon_points WHERE land_id = l.id) as point_count
    FROM lands l WHERE l.user_id = $client_user_id ORDER BY l.created_at DESC");

$current_year = date('Y');
$payment_check = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM user_payments WHERE user_id = $client_user_id AND payment_year = $current_year AND status = 'confirmed'"));
$is_paid = $payment_check ? true : false;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($client['full_name']); ?>'s Lands - Uhakiki Madalali</title>
    <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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        :root {
            --primary: #1a3a6e;
            --secondary: #2d5a3d;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #0ea5e9;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-500: #64748b;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --sidebar-width: 280px;
            --radius: 12px;
            --radius-lg: 16px;
        }

        body { background: var(--gray-100); min-height: 100vh; }
        .app-main { margin-left: var(--sidebar-width); min-height: 100vh; padding: 24px; }
        @media (max-width: 1024px) { .app-main { margin-left: 0; padding: 16px; } }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: var(--gray-500);
            text-decoration: none;
            font-size: 14px;
            margin-bottom: 16px;
        }

        .back-link:hover { color: var(--primary); }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 24px;
            color: white;
        }

        .client-header {
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }

        .client-avatar {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            font-weight: 700;
        }

        .client-info h1 {
            font-size: 24px;
            font-weight: 700;
            margin: 0 0 6px;
        }

        .client-info p {
            margin: 0;
            opacity: 0.9;
            font-size: 14px;
        }

        .payment-badge {
            margin-left: auto;
            padding: 12px 24px;
            border-radius: 12px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .payment-badge.paid { background: rgba(34, 197, 94, 0.2); }
        .payment-badge.unpaid { background: rgba(239, 68, 68, 0.2); }

        .view-only-notice {
            background: rgba(14, 165, 233, 0.1);
            border-left: 4px solid var(--info);
            padding: 14px 20px;
            border-radius: 10px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
            color: #0c5460;
        }

        .lands-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
        }

        .land-card {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
            overflow: hidden;
            transition: all 0.3s;
        }

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

        .land-card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            color: white;
        }

        .land-card-header h3 {
            font-size: 18px;
            font-weight: 600;
            margin: 0 0 8px;
        }

        .land-card-header p {
            margin: 0;
            opacity: 0.9;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

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

        .land-stats {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;
        }

        .land-stat {
            flex: 1;
            text-align: center;
            padding: 12px;
            background: var(--gray-50);
            border-radius: var(--radius);
        }

        .land-stat h4 {
            font-size: 20px;
            font-weight: 700;
            color: var(--primary);
            margin: 0;
        }

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

        .land-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .meta-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
        }

        .meta-badge.status { background: rgba(34, 197, 94, 0.1); color: var(--success); }
        .meta-badge.date { background: var(--gray-100); color: var(--gray-500); }
        .meta-badge.shared { background: rgba(14, 165, 233, 0.1); color: var(--info); }

        .view-btn {
            display: block;
            text-align: center;
            padding: 12px;
            background: var(--primary);
            color: white;
            text-decoration: none;
            font-weight: 500;
            font-size: 14px;
            border-radius: var(--radius);
            margin-top: 16px;
            transition: all 0.2s;
        }

        .view-btn:hover {
            background: var(--secondary);
            color: white;
        }

        .empty-state {
            background: white;
            border-radius: var(--radius-lg);
            padding: 60px;
            text-align: center;
        }

        .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 20px;
            font-size: 32px;
            color: var(--gray-400);
        }

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

        @media (max-width: 768px) {
            .client-header { flex-direction: column; align-items: flex-start; }
            .payment-badge { margin-left: 0; margin-top: 12px; }
            .lands-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <a href="<?php echo url('my-clients'); ?>" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to My Clients
        </a>

        <div class="page-header">
            <div class="client-header">
                <div class="client-avatar">
                    <?php echo strtoupper(substr($client['full_name'] ?: $client['username'], 0, 1)); ?>
                </div>
                <div class="client-info">
                    <h1><?php echo htmlspecialchars($client['full_name'] ?: $client['username']); ?></h1>
                    <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($client['phone'] ?: 'No phone'); ?> | <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($client['email'] ?: 'No email'); ?></p>
                </div>
                <div class="payment-badge <?php echo $is_paid ? 'paid' : 'unpaid'; ?>">
                    <i class="fas fa-<?php echo $is_paid ? 'check-circle' : 'times-circle'; ?>"></i>
                    <?php echo $is_paid ? 'Paid ' . $current_year : 'Unpaid ' . $current_year; ?>
                </div>
            </div>
        </div>

        <div class="view-only-notice">
            <i class="fas fa-info-circle"></i>
            <span>You have view-only access to this client's lands. You cannot edit or delete their records.</span>
        </div>

        <?php if(mysqli_num_rows($lands_result) == 0): ?>
        <div class="empty-state">
            <div class="empty-state-icon"><i class="fas fa-map"></i></div>
            <h3>No Lands Registered</h3>
            <p>This client hasn't registered any lands yet.</p>
        </div>
        <?php else: ?>
        <div class="lands-grid">
            <?php while($land = mysqli_fetch_assoc($lands_result)): ?>
            <div class="land-card">
                <div class="land-card-header">
                    <h3><?php echo htmlspecialchars($land['land_name']); ?></h3>
                    <p><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($land['location_address'] ?: 'Location not specified'); ?></p>
                </div>
                <div class="land-card-body">
                    <div class="land-stats">
                        <div class="land-stat">
                            <h4><?php echo number_format($land['total_area'], 2); ?></h4>
                            <span><?php echo $land['area_unit']; ?></span>
                        </div>
                        <div class="land-stat">
                            <h4><?php echo $land['point_count']; ?></h4>
                            <span>Beacons</span>
                        </div>
                    </div>
                    <div class="land-meta">
                        <span class="meta-badge status"><?php echo ucfirst($land['status']); ?></span>
                        <span class="meta-badge date"><i class="fas fa-calendar"></i> <?php echo date('d M Y', strtotime($land['created_at'])); ?></span>
                        <?php if($land['share_token']): ?>
                        <span class="meta-badge shared"><i class="fas fa-share-alt"></i> Shared</span>
                        <?php endif; ?>
                    </div>
                    <a href="<?php echo url('view-land/' . $land['id']); ?>" class="view-btn">
                        <i class="fas fa-eye"></i> View Details
                    </a>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php endif; ?>
    </main>
</body>
</html>
