<?php
/**
 * My Clients - Broker View
 * Shows clients who registered using the broker's code
 * Broker has view-only access to client lands and payment status
 */

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';

// Only brokers can access this page
if($user_role != 'broker') {
    header('Location: dashboard?error=Access denied');
    exit;
}

// Get broker's code
$broker_info = mysqli_fetch_assoc(mysqli_query($conn, "SELECT broker_code FROM users WHERE id = $user_id"));
$broker_code = $broker_info['broker_code'];

if(!$broker_code) {
    header('Location: dashboard?error=Broker code not found');
    exit;
}

$current_year = date('Y');

// Pagination
$per_page = 10;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $per_page;

// Search
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query
$where_conditions = ["referred_by_broker = $user_id", "role = 'user'"];
$where_params = [];
$param_types = '';

if(!empty($search)) {
    $search_term = "%$search%";
    $where_conditions[] = "(full_name LIKE ? OR phone LIKE ? OR email LIKE ? OR username LIKE ?)";
    $where_params[] = $search_term;
    $where_params[] = $search_term;
    $where_params[] = $search_term;
    $where_params[] = $search_term;
    $param_types .= 'ssss';
}

$where_sql = "WHERE " . implode(" AND ", $where_conditions);

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM users $where_sql";
if(!empty($where_params)) {
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param($param_types, ...$where_params);
    $count_stmt->execute();
    $total_clients = $count_stmt->get_result()->fetch_assoc()['total'];
} else {
    $total_clients = mysqli_fetch_assoc(mysqli_query($conn, $count_sql))['total'];
}

$total_pages = ceil($total_clients / $per_page);

// Get clients with payment status
$clients_sql = "SELECT u.*,
                (SELECT COUNT(*) FROM lands WHERE user_id = u.id) as land_count,
                (SELECT MAX(payment_year) FROM user_payments WHERE user_id = u.id AND status = 'confirmed') as last_paid_year
                FROM users u
                $where_sql
                ORDER BY u.created_at DESC
                LIMIT $per_page OFFSET $offset";

if(!empty($where_params)) {
    $clients_stmt = $conn->prepare($clients_sql);
    $clients_stmt->bind_param($param_types, ...$where_params);
    $clients_stmt->execute();
    $clients_result = $clients_stmt->get_result();
} else {
    $clients_result = mysqli_query($conn, $clients_sql);
}

// Statistics
$stats = [
    'total' => $total_clients,
    'active' => mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM users WHERE referred_by_broker = $user_id AND role = 'user' AND status = 'approved'"))['cnt'] ?? 0,
    'paid' => mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(DISTINCT up.user_id) as cnt FROM user_payments up JOIN users u ON up.user_id = u.id WHERE u.referred_by_broker = $user_id AND up.payment_year = $current_year AND up.status = 'confirmed'"))['cnt'] ?? 0
];

$page_title = 'My Clients';
?>
<!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; ?> - Uhakiki Madalali</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">
    <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;
            --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; }
        }

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

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

        .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;
        }

        .broker-code-display {
            background: rgba(255,255,255,0.2);
            padding: 12px 24px;
            border-radius: 12px;
            text-align: center;
        }

        .broker-code-display span {
            display: block;
            font-size: 12px;
            opacity: 0.9;
        }

        .broker-code-display strong {
            font-size: 22px;
            letter-spacing: 2px;
        }

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

        .stat-card {
            background: white;
            border-radius: var(--radius-lg);
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 16px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }

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

        .stat-icon.primary { background: linear-gradient(135deg, #667eea, #764ba2); }
        .stat-icon.success { background: linear-gradient(135deg, #22c55e, #16a34a); }
        .stat-icon.warning { background: linear-gradient(135deg, #f59e0b, #d97706); }

        .stat-content h3 {
            font-size: 26px;
            font-weight: 700;
            color: var(--gray-800);
            margin: 0;
        }

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

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

        .table-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .table-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-800);
        }

        .search-box {
            position: relative;
        }

        .search-box input {
            padding: 10px 14px 10px 40px;
            border: 2px solid var(--gray-200);
            border-radius: var(--radius);
            font-size: 14px;
            width: 280px;
        }

        .search-box input:focus {
            outline: none;
            border-color: var(--primary);
        }

        .search-box i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-500);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th {
            padding: 14px 20px;
            text-align: left;
            font-size: 12px;
            font-weight: 600;
            color: var(--gray-500);
            text-transform: uppercase;
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table td {
            padding: 16px 20px;
            font-size: 14px;
            color: var(--gray-700);
            border-bottom: 1px solid var(--gray-100);
        }

        .data-table tbody tr:hover {
            background: var(--gray-50);
        }

        .client-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .client-avatar {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            background: linear-gradient(135deg, #11998e, #38ef7d);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 16px;
        }

        .client-details h4 {
            font-size: 14px;
            font-weight: 600;
            color: var(--gray-800);
            margin: 0 0 2px;
        }

        .client-details span {
            font-size: 12px;
            color: var(--gray-500);
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-success {
            background: rgba(34, 197, 94, 0.1);
            color: var(--success);
        }

        .badge-warning {
            background: rgba(245, 158, 11, 0.1);
            color: var(--warning);
        }

        .badge-danger {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
        }

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

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 8px 16px;
            border-radius: var(--radius);
            font-size: 13px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.2s;
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--gray-200);
            color: var(--gray-600);
        }

        .btn-outline:hover {
            border-color: var(--primary);
            color: var(--primary);
        }

        .btn-icon {
            width: 34px;
            height: 34px;
            padding: 0;
            border-radius: 8px;
        }

        .table-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .table-info {
            font-size: 13px;
            color: var(--gray-500);
        }

        .pagination {
            display: flex;
            gap: 6px;
        }

        .pagination a, .pagination span {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 500;
            text-decoration: none;
        }

        .pagination a {
            background: white;
            color: var(--gray-600);
            border: 1px solid var(--gray-200);
        }

        .pagination a:hover {
            background: var(--gray-100);
        }

        .pagination .active {
            background: var(--primary);
            color: white;
        }

        .pagination .disabled {
            background: var(--gray-100);
            color: var(--gray-400);
            cursor: not-allowed;
        }

        .empty-state {
            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;
        }

        .empty-state-icon i {
            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);
        }

        .table-wrapper {
            overflow-x: auto;
        }

        @media (max-width: 768px) {
            .page-header-content { flex-direction: column; align-items: flex-start; }
            .table-header { flex-direction: column; align-items: stretch; }
            .search-box input { width: 100%; }
            .data-table { min-width: 700px; }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-users"></i> My Clients</h1>
                    <p>Clients who registered using your broker code</p>
                </div>
                <div class="broker-code-display">
                    <span>Your Broker Code</span>
                    <strong><?php echo htmlspecialchars($broker_code); ?></strong>
                </div>
            </div>
        </div>

        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon primary"><i class="fas fa-users"></i></div>
                <div class="stat-content">
                    <h3><?php echo number_format($stats['total']); ?></h3>
                    <p>Total Clients</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon success"><i class="fas fa-user-check"></i></div>
                <div class="stat-content">
                    <h3><?php echo number_format($stats['active']); ?></h3>
                    <p>Active (Approved)</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon warning"><i class="fas fa-receipt"></i></div>
                <div class="stat-content">
                    <h3><?php echo number_format($stats['paid']); ?></h3>
                    <p>Paid <?php echo $current_year; ?></p>
                </div>
            </div>
        </div>

        <div class="table-card">
            <div class="table-header">
                <h3 class="table-title">All Referred Clients</h3>
                <form class="search-box" method="GET">
                    <i class="fas fa-search"></i>
                    <input type="text" name="search" placeholder="Search clients..." value="<?php echo htmlspecialchars($search); ?>">
                </form>
            </div>

            <?php if(mysqli_num_rows($clients_result) == 0): ?>
            <div class="empty-state">
                <div class="empty-state-icon"><i class="fas fa-users"></i></div>
                <h3>No Clients Yet</h3>
                <p>Share your broker code <strong><?php echo htmlspecialchars($broker_code); ?></strong> with clients so they can register under you.</p>
            </div>
            <?php else: ?>
            <div class="table-wrapper">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Client</th>
                        <th>Phone</th>
                        <th>Registered</th>
                        <th>Lands</th>
                        <th>Account Status</th>
                        <th>Payment</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($client = mysqli_fetch_assoc($clients_result)):
                        $is_paid = $client['last_paid_year'] >= $current_year;
                        $initials = strtoupper(substr($client['full_name'] ?: $client['username'], 0, 1));
                    ?>
                    <tr>
                        <td>
                            <div class="client-info">
                                <div class="client-avatar"><?php echo $initials; ?></div>
                                <div class="client-details">
                                    <h4><?php echo htmlspecialchars($client['full_name'] ?: $client['username']); ?></h4>
                                    <span><?php echo htmlspecialchars($client['email'] ?: '-'); ?></span>
                                </div>
                            </div>
                        </td>
                        <td><?php echo htmlspecialchars($client['phone'] ?: '-'); ?></td>
                        <td><?php echo date('d M Y', strtotime($client['created_at'])); ?></td>
                        <td><span class="badge badge-info"><?php echo $client['land_count']; ?> lands</span></td>
                        <td>
                            <?php if($client['status'] == 'approved'): ?>
                            <span class="badge badge-success"><i class="fas fa-check"></i> Active</span>
                            <?php elseif($client['status'] == 'pending'): ?>
                            <span class="badge badge-warning"><i class="fas fa-clock"></i> Pending</span>
                            <?php else: ?>
                            <span class="badge badge-danger"><?php echo ucfirst($client['status']); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if($is_paid): ?>
                            <span class="badge badge-success"><i class="fas fa-check"></i> Paid</span>
                            <?php else: ?>
                            <span class="badge badge-danger"><i class="fas fa-times"></i> Unpaid</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="<?php echo url('client-lands/' . $client['id']); ?>" class="btn btn-outline btn-icon" title="View Lands">
                                <i class="fas fa-map"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            </div>

            <div class="table-footer">
                <div class="table-info">
                    Showing <?php echo min($offset + 1, $total_clients); ?> to <?php echo min($offset + $per_page, $total_clients); ?> of <?php echo $total_clients; ?> clients
                </div>
                <?php if($total_pages > 1): ?>
                <div class="pagination">
                    <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                    <?php else: ?>
                    <span class="disabled"><i class="fas fa-chevron-left"></i></span>
                    <?php endif; ?>

                    <?php for($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                    <?php if($i == $page): ?>
                    <span class="active"><?php echo $i; ?></span>
                    <?php else: ?>
                    <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                    <?php endif; ?>
                    <?php endfor; ?>

                    <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php else: ?>
                    <span class="disabled"><i class="fas fa-chevron-right"></i></span>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </main>

    <script src="assets/js/offline-storage.js"></script>
</body>
</html>
