<?php
/**
 * Client Management
 * Manage clients for brokers and admins
 */

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 and admins can manage clients
if(!in_array($user_role, ['broker', 'admin'])) {
    header('Location: dashboard?error=Access denied');
    exit;
}

$error = '';
$success = '';

// Handle actions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';

    if($action == 'add_client') {
        $full_name = trim($_POST['full_name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $national_id = trim($_POST['national_id']);
        $address = trim($_POST['address']);
        $notes = trim($_POST['notes']);
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        if(empty($full_name) || empty($phone)) {
            $error = 'Full name and phone number are required';
        } else {
            // Check if phone already exists for this broker
            $check_stmt = $conn->prepare("SELECT id FROM clients WHERE phone = ? AND broker_id = ?");
            $check_stmt->bind_param("si", $phone, $user_id);
            $check_stmt->execute();

            if($check_stmt->get_result()->num_rows > 0) {
                $error = 'A client with this phone number already exists';
            } else {
                // Check if username already exists (if provided)
                if(!empty($username)) {
                    $username_check = $conn->prepare("SELECT id FROM clients WHERE username = ?");
                    $username_check->bind_param("s", $username);
                    $username_check->execute();
                    if($username_check->get_result()->num_rows > 0) {
                        $error = 'This username is already taken';
                    }
                    // Also check users table
                    if(empty($error)) {
                        $user_check = $conn->prepare("SELECT id FROM users WHERE username = ?");
                        $user_check->bind_param("s", $username);
                        $user_check->execute();
                        if($user_check->get_result()->num_rows > 0) {
                            $error = 'This username is already taken';
                        }
                    }
                }

                if(empty($error)) {
                    // Hash password if provided
                    $hashed_password = !empty($password) ? password_hash($password, PASSWORD_DEFAULT) : null;
                    $username = !empty($username) ? $username : null;

                    $insert_stmt = $conn->prepare("INSERT INTO clients (broker_id, username, password, full_name, email, phone, national_id, address, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $insert_stmt->bind_param("issssssss", $user_id, $username, $hashed_password, $full_name, $email, $phone, $national_id, $address, $notes);

                    if($insert_stmt->execute()) {
                        $success = 'Client added successfully' . ($username ? ' with login credentials' : '');
                    } else {
                        $error = 'Failed to add client';
                    }
                }
            }
        }
    }

    if($action == 'update_client') {
        $client_id = intval($_POST['client_id']);
        $full_name = trim($_POST['full_name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $national_id = trim($_POST['national_id']);
        $address = trim($_POST['address']);
        $notes = trim($_POST['notes']);
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        // Verify ownership
        if($user_role == 'admin') {
            $check_stmt = $conn->prepare("SELECT id, username FROM clients WHERE id = ?");
            $check_stmt->bind_param("i", $client_id);
        } else {
            $check_stmt = $conn->prepare("SELECT id, username FROM clients WHERE id = ? AND broker_id = ?");
            $check_stmt->bind_param("ii", $client_id, $user_id);
        }
        $check_stmt->execute();
        $client_result = $check_stmt->get_result();

        if($client_result->num_rows == 0) {
            $error = 'Client not found or access denied';
        } else {
            $existing_client = $client_result->fetch_assoc();

            // Check if new username is taken (if changed)
            if(!empty($username) && $username !== $existing_client['username']) {
                $username_check = $conn->prepare("SELECT id FROM clients WHERE username = ? AND id != ?");
                $username_check->bind_param("si", $username, $client_id);
                $username_check->execute();
                if($username_check->get_result()->num_rows > 0) {
                    $error = 'This username is already taken';
                }
                // Also check users table
                if(empty($error)) {
                    $user_check = $conn->prepare("SELECT id FROM users WHERE username = ?");
                    $user_check->bind_param("s", $username);
                    $user_check->execute();
                    if($user_check->get_result()->num_rows > 0) {
                        $error = 'This username is already taken';
                    }
                }
            }

            if(empty($error)) {
                // Update with or without password
                if(!empty($password)) {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $update_stmt = $conn->prepare("UPDATE clients SET full_name = ?, email = ?, phone = ?, national_id = ?, address = ?, notes = ?, username = ?, password = ? WHERE id = ?");
                    $username = !empty($username) ? $username : null;
                    $update_stmt->bind_param("ssssssssi", $full_name, $email, $phone, $national_id, $address, $notes, $username, $hashed_password, $client_id);
                } else {
                    $update_stmt = $conn->prepare("UPDATE clients SET full_name = ?, email = ?, phone = ?, national_id = ?, address = ?, notes = ?, username = ? WHERE id = ?");
                    $username = !empty($username) ? $username : null;
                    $update_stmt->bind_param("sssssssi", $full_name, $email, $phone, $national_id, $address, $notes, $username, $client_id);
                }

                if($update_stmt->execute()) {
                    $success = 'Client updated successfully';
                } else {
                    $error = 'Failed to update client';
                }
            }
        }
    }

    if($action == 'toggle_status') {
        $client_id = intval($_POST['client_id']);
        $new_status = $_POST['new_status'];

        // Only admin can change status
        if($user_role != 'admin') {
            $error = 'Only administrators can change client status';
        } else {
            $status_stmt = $conn->prepare("UPDATE clients SET access_status = ? WHERE id = ?");
            $status_stmt->bind_param("si", $new_status, $client_id);

            if($status_stmt->execute()) {
                $success = 'Client status updated';
            } else {
                $error = 'Failed to update status';
            }
        }
    }

    if($action == 'delete_client') {
        $client_id = intval($_POST['client_id']);

        // Verify ownership
        if($user_role == 'admin') {
            $check_stmt = $conn->prepare("SELECT id FROM clients WHERE id = ?");
            $check_stmt->bind_param("i", $client_id);
        } else {
            $check_stmt = $conn->prepare("SELECT id FROM clients WHERE id = ? AND broker_id = ?");
            $check_stmt->bind_param("ii", $client_id, $user_id);
        }
        $check_stmt->execute();

        if($check_stmt->get_result()->num_rows == 0) {
            $error = 'Client not found or access denied';
        } else {
            // Check if client has lands
            $lands_stmt = $conn->prepare("SELECT COUNT(*) as cnt FROM lands WHERE client_id = ?");
            $lands_stmt->bind_param("i", $client_id);
            $lands_stmt->execute();
            $lands_count = $lands_stmt->get_result()->fetch_assoc()['cnt'];

            if($lands_count > 0) {
                $error = "Cannot delete client with $lands_count registered land(s). Remove the lands first.";
            } else {
                $delete_stmt = $conn->prepare("DELETE FROM clients WHERE id = ?");
                $delete_stmt->bind_param("i", $client_id);

                if($delete_stmt->execute()) {
                    $success = 'Client deleted successfully';
                } else {
                    $error = 'Failed to delete client';
                }
            }
        }
    }
}

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

// Search and filter
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';
$payment_filter = isset($_GET['payment']) ? trim($_GET['payment']) : '';

// Build WHERE clause
$where_conditions = [];
$where_params = [];
$param_types = '';

if($user_role != 'admin') {
    $where_conditions[] = "c.broker_id = ?";
    $where_params[] = $user_id;
    $param_types .= 'i';
}

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

if(!empty($status_filter)) {
    $where_conditions[] = "c.access_status = ?";
    $where_params[] = $status_filter;
    $param_types .= 's';
}

$where_sql = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM clients c $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 pagination
$current_year = date('Y');
if($user_role == 'admin') {
    $clients_sql = "SELECT c.*, u.full_name as broker_name, u.username as broker_username,
                    (SELECT COUNT(*) FROM lands WHERE client_id = c.id) as land_count,
                    (SELECT MAX(payment_year) FROM client_payments WHERE client_id = c.id AND status = 'confirmed') as last_paid_year
                    FROM clients c
                    JOIN users u ON c.broker_id = u.id
                    $where_sql
                    ORDER BY c.created_at DESC
                    LIMIT $per_page OFFSET $offset";
} else {
    $clients_sql = "SELECT c.*,
                    (SELECT COUNT(*) FROM lands WHERE client_id = c.id) as land_count,
                    (SELECT MAX(payment_year) FROM client_payments WHERE client_id = c.id AND status = 'confirmed') as last_paid_year
                    FROM clients c
                    $where_sql
                    ORDER BY c.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);
}

// Get statistics (without pagination)
$stats_where = $user_role != 'admin' ? "WHERE c.broker_id = $user_id" : "";
$stats_sql = "SELECT
    COUNT(*) as total,
    SUM(CASE WHEN c.access_status = 'active' THEN 1 ELSE 0 END) as active_count,
    SUM((SELECT COUNT(*) FROM lands WHERE client_id = c.id)) as total_lands
    FROM clients c $stats_where";
$stats = mysqli_fetch_assoc(mysqli_query($conn, $stats_sql));
$active_count = $stats['active_count'] ?? 0;
$total_lands = $stats['total_lands'] ?? 0;

// Count paid clients
$paid_sql = "SELECT COUNT(DISTINCT c.id) as paid FROM clients c
             INNER JOIN client_payments cp ON c.id = cp.client_id
             WHERE cp.payment_year = $current_year AND cp.status = 'confirmed'";
if($user_role != 'admin') {
    $paid_sql .= " AND c.broker_id = $user_id";
}
$paid_count = mysqli_fetch_assoc(mysqli_query($conn, $paid_sql))['paid'] ?? 0;

$page_title = 'Client Management';
$current_page = '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;
            --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;
            --sidebar-width: 280px;
            --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);
            --radius: 12px;
            --radius-lg: 16px;
        }

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

        .app-main {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }

        @media (max-width: 1024px) {
            .app-main {
                margin-left: 0;
            }
        }

        .page-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            padding: 32px 32px 80px;
            color: white;
        }

        .page-header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 16px;
        }

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

        .page-subtitle {
            font-size: 15px;
            opacity: 0.9;
        }

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

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

        .btn-white:hover {
            background: var(--gray-100);
            transform: translateY(-1px);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
        }

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

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

        .btn-sm {
            padding: 6px 12px;
            font-size: 13px;
        }

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

        .content-container {
            max-width: 1400px;
            margin: -50px auto 0;
            padding: 0 32px 32px;
            position: relative;
            z-index: 10;
        }

        @media (max-width: 768px) {
            .page-header {
                padding: 24px 20px 70px;
            }
            .content-container {
                padding: 0 16px 24px;
            }
            .page-title {
                font-size: 22px;
            }
        }

        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 16px;
            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;
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            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: 24px;
            font-weight: 700;
            color: var(--gray-800);
        }

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

        .alert {
            padding: 14px 18px;
            border-radius: var(--radius);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }

        .alert-close {
            margin-left: auto;
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            opacity: 0.5;
        }

        .table-card {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow);
            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: 16px;
            font-weight: 600;
            color: var(--gray-800);
        }

        .table-filters {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .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: 250px;
            transition: all 0.2s;
        }

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

        .filter-select {
            padding: 10px 14px;
            border: 2px solid var(--gray-200);
            border-radius: var(--radius);
            font-size: 14px;
            background: white;
            cursor: pointer;
        }

        .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;
            letter-spacing: 0.5px;
            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);
            vertical-align: middle;
        }

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

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

        .client-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 14px;
            flex-shrink: 0;
        }

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

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

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            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);
        }

        .badge-warning {
            background: rgba(255, 193, 7, 0.15);
            color: #9a6700;
        }

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

        .actions-cell {
            display: flex;
            gap: 6px;
        }

        /* Make actions column sticky on right */
        .data-table th:last-child,
        .data-table td:last-child {
            position: sticky;
            right: 0;
            background: white;
            box-shadow: -4px 0 8px rgba(0,0,0,0.05);
        }

        .data-table th:last-child {
            background: var(--gray-50);
        }

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

        .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;
            transition: all 0.2s;
        }

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

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

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

        .pagination .disabled {
            background: var(--gray-100);
            color: var(--gray-400);
            border: 1px solid var(--gray-200);
            cursor: not-allowed;
        }

        .empty-state {
            padding: 60px 40px;
            text-align: center;
        }

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

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

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

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

        /* Modal */
        .modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }

        .modal-backdrop.active {
            opacity: 1;
            visibility: visible;
        }

        .modal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
            z-index: 9999;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }

        .modal.active {
            opacity: 1;
            visibility: visible;
            transform: translate(-50%, -50%) scale(1);
        }

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

        .modal-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: var(--gray-800);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .modal-close {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            border: none;
            background: var(--gray-100);
            color: var(--gray-500);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-close:hover {
            background: var(--gray-200);
        }

        .modal-body {
            padding: 24px;
        }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 6px;
        }

        .form-label .required {
            color: var(--danger);
        }

        .form-control {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid var(--gray-200);
            border-radius: var(--radius);
            font-size: 14px;
            transition: all 0.2s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
        }

        textarea.form-control {
            resize: vertical;
            min-height: 70px;
        }

        .input-icon-wrapper {
            position: relative;
        }

        .input-icon-wrapper .form-control {
            padding-left: 40px;
        }

        .input-icon-wrapper i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-400);
        }

        .credentials-section {
            border-top: 2px solid var(--gray-200);
            margin-top: 20px;
            padding-top: 20px;
        }

        .credentials-section h4 {
            font-size: 14px;
            color: var(--gray-700);
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

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

        .credentials-section p {
            font-size: 12px;
            color: var(--gray-500);
            margin-bottom: 12px;
        }

        .login-status {
            font-size: 12px;
            padding: 8px 12px;
            border-radius: 8px;
            margin-bottom: 12px;
        }

        .toast-container {
            position: fixed;
            bottom: 24px;
            right: 24px;
            z-index: 9999;
        }

        .toast {
            background: var(--gray-800);
            color: white;
            padding: 14px 20px;
            border-radius: var(--radius);
            box-shadow: 0 10px 25px -5px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            gap: 10px;
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s ease;
        }

        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }

        .toast.success {
            background: linear-gradient(135deg, var(--secondary), var(--secondary-light));
        }

        .table-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }
            .table-header {
                flex-direction: column;
                align-items: stretch;
            }
            .table-filters {
                flex-direction: column;
            }
            .search-box input {
                width: 100%;
            }
            .data-table {
                min-width: 800px;
            }
            .table-footer {
                flex-direction: column;
                text-align: center;
            }
            .page-header {
                padding: 24px 16px 70px;
            }
            .content-container {
                padding: 0 16px 24px;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="page-header">
            <div class="page-header-content">
                <div>
                    <h1 class="page-title">
                        <i class="fas fa-users"></i>
                        Client Management
                    </h1>
                    <p class="page-subtitle">Manage your clients and their land registrations</p>
                </div>
                <button class="btn btn-white" onclick="openModal('addClientModal')">
                    <i class="fas fa-plus"></i>
                    Add Client
                </button>
            </div>
        </div>

        <div class="content-container">
            <!-- Stats -->
            <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($total_clients); ?></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($active_count); ?></h3>
                        <p>Active</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($paid_count); ?></h3>
                        <p>Paid <?php echo $current_year; ?></p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon info"><i class="fas fa-map"></i></div>
                    <div class="stat-content">
                        <h3><?php echo number_format($total_lands); ?></h3>
                        <p>Total Lands</p>
                    </div>
                </div>
            </div>

            <?php if($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo htmlspecialchars($error); ?>
                <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
            </div>
            <?php endif; ?>

            <?php if($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo htmlspecialchars($success); ?>
                <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
            </div>
            <?php endif; ?>

            <!-- Table Card -->
            <div class="table-card">
                <div class="table-header">
                    <h3 class="table-title">All Clients</h3>
                    <form class="table-filters" method="GET">
                        <div class="search-box">
                            <i class="fas fa-search"></i>
                            <input type="text" name="search" placeholder="Search clients..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <select name="status" class="filter-select" onchange="this.form.submit()">
                            <option value="">All Status</option>
                            <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="suspended" <?php echo $status_filter == 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                            <option value="expired" <?php echo $status_filter == 'expired' ? 'selected' : ''; ?>>Expired</option>
                        </select>
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                        <?php if($search || $status_filter): ?>
                        <a href="clients" class="btn btn-outline btn-sm">Clear</a>
                        <?php endif; ?>
                    </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 Found</h3>
                    <p><?php echo $search ? 'No clients match your search criteria' : 'Start adding clients to manage their land registrations'; ?></p>
                    <?php if(!$search): ?>
                    <button class="btn btn-primary" onclick="openModal('addClientModal')">
                        <i class="fas fa-plus"></i> Add First Client
                    </button>
                    <?php endif; ?>
                </div>
                <?php else: ?>
                <div class="table-wrapper">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Client</th>
                            <th>Phone</th>
                            <th>Lands</th>
                            <th>Status</th>
                            <th>Payment</th>
                            <th>Login</th>
                            <?php if($user_role == 'admin'): ?>
                            <th>Broker</th>
                            <?php endif; ?>
                            <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'], 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']); ?></h4>
                                        <span><?php echo $client['national_id'] ? 'ID: ' . htmlspecialchars($client['national_id']) : ($client['email'] ?: '-'); ?></span>
                                    </div>
                                </div>
                            </td>
                            <td><?php echo htmlspecialchars($client['phone']); ?></td>
                            <td><span class="badge badge-info"><?php echo $client['land_count']; ?> lands</span></td>
                            <td>
                                <span class="badge badge-<?php echo $client['access_status'] == 'active' ? 'success' : ($client['access_status'] == 'suspended' ? 'danger' : 'warning'); ?>">
                                    <?php echo ucfirst($client['access_status']); ?>
                                </span>
                            </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>
                                <?php if($client['username']): ?>
                                <span class="badge badge-info" title="Username: <?php echo htmlspecialchars($client['username']); ?>">
                                    <i class="fas fa-key"></i> Enabled
                                </span>
                                <?php else: ?>
                                <span class="badge badge-warning">No Login</span>
                                <?php endif; ?>
                            </td>
                            <?php if($user_role == 'admin'): ?>
                            <td><?php echo htmlspecialchars($client['broker_name'] ?: $client['broker_username']); ?></td>
                            <?php endif; ?>
                            <td>
                                <div class="actions-cell">
                                    <button class="btn btn-outline btn-icon" onclick='editClient(<?php echo json_encode($client); ?>)' title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a href="<?php echo url('client/' . $client['id'] . '/payments'); ?>" class="btn btn-outline btn-icon" title="Payments">
                                        <i class="fas fa-money-bill"></i>
                                    </a>
                                    <a href="<?php echo url('add-land?client_id=' . $client['id']); ?>" class="btn btn-outline btn-icon" title="Add Land">
                                        <i class="fas fa-map-marker-alt"></i>
                                    </a>
                                </div>
                            </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); ?>&status=<?php echo urlencode($status_filter); ?>">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php else: ?>
                        <span class="disabled"><i class="fas fa-chevron-left"></i></span>
                        <?php endif; ?>

                        <?php
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);

                        if($start_page > 1): ?>
                        <a href="?page=1&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>">1</a>
                        <?php if($start_page > 2): ?><span class="disabled">...</span><?php endif; ?>
                        <?php endif; ?>

                        <?php for($i = $start_page; $i <= $end_page; $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); ?>&status=<?php echo urlencode($status_filter); ?>"><?php echo $i; ?></a>
                        <?php endif; ?>
                        <?php endfor; ?>

                        <?php if($end_page < $total_pages): ?>
                        <?php if($end_page < $total_pages - 1): ?><span class="disabled">...</span><?php endif; ?>
                        <a href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>"><?php echo $total_pages; ?></a>
                        <?php endif; ?>

                        <?php if($page < $total_pages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>">
                            <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>
        </div>
    </main>

    <!-- Modal Backdrop -->
    <div class="modal-backdrop" id="modalBackdrop" onclick="closeAllModals()"></div>

    <!-- Add Client Modal -->
    <div class="modal" id="addClientModal">
        <div class="modal-header">
            <h3><i class="fas fa-user-plus"></i> Add New Client</h3>
            <button class="modal-close" onclick="closeModal('addClientModal')"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="add_client">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Full Name <span class="required">*</span></label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-user"></i>
                        <input type="text" name="full_name" class="form-control" required placeholder="Enter full name">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Phone <span class="required">*</span></label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-phone"></i>
                        <input type="text" name="phone" class="form-control" required placeholder="+255...">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-envelope"></i>
                        <input type="email" name="email" class="form-control" placeholder="email@example.com">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">National ID</label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-id-card"></i>
                        <input type="text" name="national_id" class="form-control" placeholder="National ID">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Address</label>
                    <textarea name="address" class="form-control" rows="2" placeholder="Client address"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="2" placeholder="Additional notes"></textarea>
                </div>
                <div class="credentials-section">
                    <h4><i class="fas fa-key"></i> Login Credentials (Optional)</h4>
                    <p>Create login credentials so this client can access their lands</p>
                    <div class="form-group">
                        <label class="form-label">Username</label>
                        <div class="input-icon-wrapper">
                            <i class="fas fa-at"></i>
                            <input type="text" name="username" class="form-control" placeholder="Client username">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <div class="input-icon-wrapper">
                            <i class="fas fa-lock"></i>
                            <input type="password" name="password" class="form-control" placeholder="Client password">
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal('addClientModal')">Cancel</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-plus"></i> Add Client</button>
            </div>
        </form>
    </div>

    <!-- Edit Client Modal -->
    <div class="modal" id="editClientModal">
        <div class="modal-header">
            <h3><i class="fas fa-edit"></i> Edit Client</h3>
            <button class="modal-close" onclick="closeModal('editClientModal')"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="update_client">
            <input type="hidden" name="client_id" id="edit_client_id">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Full Name <span class="required">*</span></label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-user"></i>
                        <input type="text" name="full_name" id="edit_full_name" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Phone <span class="required">*</span></label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-phone"></i>
                        <input type="text" name="phone" id="edit_phone" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-envelope"></i>
                        <input type="email" name="email" id="edit_email" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">National ID</label>
                    <div class="input-icon-wrapper">
                        <i class="fas fa-id-card"></i>
                        <input type="text" name="national_id" id="edit_national_id" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Address</label>
                    <textarea name="address" id="edit_address" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" id="edit_notes" class="form-control" rows="2"></textarea>
                </div>
                <div class="credentials-section">
                    <h4><i class="fas fa-key"></i> Login Credentials</h4>
                    <div id="edit_login_status" class="login-status"></div>
                    <div class="form-group">
                        <label class="form-label">Username</label>
                        <div class="input-icon-wrapper">
                            <i class="fas fa-at"></i>
                            <input type="text" name="username" id="edit_username" class="form-control" placeholder="Client username">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">New Password</label>
                        <div class="input-icon-wrapper">
                            <i class="fas fa-lock"></i>
                            <input type="password" name="password" id="edit_password" class="form-control" placeholder="Leave blank to keep current">
                        </div>
                        <small style="color: var(--gray-500); font-size: 11px;">Leave blank to keep current password</small>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal('editClientModal')">Cancel</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Update</button>
            </div>
        </form>
    </div>

    <!-- Toast -->
    <div class="toast-container">
        <div class="toast" id="toast">
            <i class="fas fa-check-circle"></i>
            <span id="toastMessage">Success!</span>
        </div>
    </div>

    <script src="assets/js/offline-storage.js"></script>
    <script>
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js').catch(err => console.log('SW error:', err));
        }

        function openModal(id) {
            document.getElementById('modalBackdrop').classList.add('active');
            document.getElementById(id).classList.add('active');
        }

        function closeModal(id) {
            document.getElementById('modalBackdrop').classList.remove('active');
            document.getElementById(id).classList.remove('active');
        }

        function closeAllModals() {
            document.querySelectorAll('.modal').forEach(m => m.classList.remove('active'));
            document.getElementById('modalBackdrop').classList.remove('active');
        }

        function editClient(client) {
            document.getElementById('edit_client_id').value = client.id;
            document.getElementById('edit_full_name').value = client.full_name;
            document.getElementById('edit_phone').value = client.phone;
            document.getElementById('edit_email').value = client.email || '';
            document.getElementById('edit_national_id').value = client.national_id || '';
            document.getElementById('edit_address').value = client.address || '';
            document.getElementById('edit_notes').value = client.notes || '';
            document.getElementById('edit_username').value = client.username || '';
            document.getElementById('edit_password').value = '';

            const status = document.getElementById('edit_login_status');
            if (client.username) {
                status.innerHTML = '<i class="fas fa-check-circle"></i> Login enabled: <strong>' + client.username + '</strong>';
                status.style.background = 'rgba(40, 167, 69, 0.1)';
                status.style.color = '#155724';
            } else {
                status.innerHTML = '<i class="fas fa-info-circle"></i> No login credentials set';
                status.style.background = 'rgba(14, 165, 233, 0.1)';
                status.style.color = '#0c5460';
            }

            openModal('editClientModal');
        }

        function showToast(msg, type = 'success') {
            const toast = document.getElementById('toast');
            document.getElementById('toastMessage').textContent = msg;
            toast.className = 'toast ' + type + ' show';
            setTimeout(() => toast.classList.remove('show'), 3000);
        }

        <?php if($success): ?>
        showToast('<?php echo addslashes($success); ?>');
        <?php endif; ?>

        document.addEventListener('keydown', e => { if (e.key === 'Escape') closeAllModals(); });
    </script>
</body>
</html>
