<?php
session_start();
require_once '../db_connect.php';

if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header('Location: ../login');
    exit;
}

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

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

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

        if(in_array($new_status, ['active', 'suspended', 'expired'])) {
            mysqli_query($conn, "UPDATE clients SET access_status = '$new_status' WHERE id = $client_id");
            $success = 'Client status updated';
        }
    }

    if($action == 'delete_client') {
        $client_id = intval($_POST['client_id']);
        $lands_check = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM lands WHERE client_id = $client_id");
        $lands_count = mysqli_fetch_assoc($lands_check)['cnt'];

        if($lands_count > 0) {
            $error = "Cannot delete client with $lands_count registered land(s)";
        } else {
            mysqli_query($conn, "DELETE FROM clients WHERE id = $client_id");
            $success = 'Client deleted';
        }
    }

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

        $check = mysqli_query($conn, "SELECT id FROM users WHERE id = $new_broker_id AND role IN ('broker', 'admin')");
        if(mysqli_num_rows($check) > 0) {
            mysqli_query($conn, "UPDATE clients SET broker_id = $new_broker_id WHERE id = $client_id");
            $success = 'Client reassigned to new broker';
        } else {
            $error = 'Invalid broker selected';
        }
    }
}

// Get filter parameters
$filter_broker = isset($_GET['broker_id']) ? intval($_GET['broker_id']) : 0;
$filter_status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$filter_payment = isset($_GET['payment']) ? $_GET['payment'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, trim($_GET['search'])) : '';

$current_year = date('Y');

// Build query
$where = "1=1";
if($filter_broker > 0) $where .= " AND c.broker_id = $filter_broker";
if($filter_status) $where .= " AND c.access_status = '$filter_status'";
if($search) $where .= " AND (c.full_name LIKE '%$search%' OR c.phone LIKE '%$search%' OR c.email LIKE '%$search%')";

$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,
                (SELECT SUM(amount) FROM client_payments WHERE client_id = c.id AND status = 'confirmed') as total_paid
                FROM clients c
                JOIN users u ON c.broker_id = u.id
                WHERE $where
                ORDER BY c.created_at DESC";

$clients_result = mysqli_query($conn, $clients_sql);

// Apply payment filter after fetch
$clients_arr = [];
while($c = mysqli_fetch_assoc($clients_result)) {
    if($filter_payment == 'paid' && $c['last_paid_year'] < $current_year) continue;
    if($filter_payment == 'unpaid' && $c['last_paid_year'] >= $current_year) continue;
    $clients_arr[] = $c;
}

// Get brokers for filter dropdown
$brokers = mysqli_query($conn, "SELECT id, full_name, username FROM users WHERE role IN ('broker', 'admin') ORDER BY full_name");

// Stats
$stats = [];
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM clients"));
$stats['total'] = $r['cnt'];
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM clients WHERE access_status = 'active'"));
$stats['active'] = $r['cnt'];
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM clients WHERE access_status = 'suspended'"));
$stats['suspended'] = $r['cnt'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Clients - Admin</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">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-user-friends"></i> All Clients</h1>
                    <p>View and manage all clients registered by brokers</p>
                </div>
            </div>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon purple">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $stats['total']; ?></h3>
                    <p>Total Clients</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $stats['active']; ?></h3>
                    <p>Active</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon red">
                    <i class="fas fa-user-slash"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $stats['suspended']; ?></h3>
                    <p>Suspended</p>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="filter-card">
            <form method="GET" class="filter-form">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" name="search" class="form-control" placeholder="Name, phone, email..."
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="filter-group">
                    <label>Broker</label>
                    <select name="broker_id" class="form-control">
                        <option value="">All Brokers</option>
                        <?php while($b = mysqli_fetch_assoc($brokers)): ?>
                        <option value="<?php echo $b['id']; ?>" <?php echo $filter_broker == $b['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($b['full_name'] ?: $b['username']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="">All Status</option>
                        <option value="active" <?php echo $filter_status == 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="suspended" <?php echo $filter_status == 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                        <option value="expired" <?php echo $filter_status == 'expired' ? 'selected' : ''; ?>>Expired</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Payment <?php echo $current_year; ?></label>
                    <select name="payment" class="form-control">
                        <option value="">All</option>
                        <option value="paid" <?php echo $filter_payment == 'paid' ? 'selected' : ''; ?>>Paid</option>
                        <option value="unpaid" <?php echo $filter_payment == 'unpaid' ? 'selected' : ''; ?>>Unpaid</option>
                    </select>
                </div>
                <div class="filter-actions">
                    <button type="submit" class="btn-filter">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                    <a href="clients" class="btn-clear">Clear</a>
                </div>
            </form>
        </div>

        <div class="content-card">
            <div class="card-header-custom">
                <h3><i class="fas fa-list"></i> Clients List</h3>
                <span class="result-count"><?php echo count($clients_arr); ?> found</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table modern-table">
                        <thead>
                            <tr>
                                <th>Client</th>
                                <th>Contact</th>
                                <th>Broker</th>
                                <th>Lands</th>
                                <th>Payment</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($clients_arr as $c):
                                $is_paid = $c['last_paid_year'] >= $current_year;
                            ?>
                            <tr>
                                <td>
                                    <div class="client-cell">
                                        <div class="client-avatar">
                                            <?php echo strtoupper(substr($c['full_name'], 0, 1)); ?>
                                        </div>
                                        <div class="client-info">
                                            <strong><?php echo htmlspecialchars($c['full_name']); ?></strong>
                                            <?php if($c['national_id']): ?>
                                            <span>ID: <?php echo htmlspecialchars($c['national_id']); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="contact-cell">
                                        <span class="phone"><?php echo htmlspecialchars($c['phone']); ?></span>
                                        <?php if($c['email']): ?>
                                        <span class="email"><?php echo htmlspecialchars($c['email']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($c['broker_name'] ?: $c['broker_username']); ?></td>
                                <td>
                                    <span class="land-count"><?php echo $c['land_count']; ?></span>
                                </td>
                                <td>
                                    <?php if($is_paid): ?>
                                    <span class="payment-badge paid">
                                        <i class="fas fa-check"></i> Paid <?php echo $c['last_paid_year']; ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="payment-badge unpaid">
                                        <i class="fas fa-times"></i> Unpaid
                                    </span>
                                    <?php endif; ?>
                                    <span class="total-paid">TZS <?php echo number_format($c['total_paid'] ?? 0); ?></span>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $c['access_status']; ?>">
                                        <?php echo ucfirst($c['access_status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn-action" data-toggle="dropdown">
                                            <i class="fas fa-ellipsis-v"></i>
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right">
                                            <a href="../client_payments.php?client_id=<?php echo $c['id']; ?>" class="dropdown-item">
                                                <i class="fas fa-money-bill mr-2"></i>View Payments
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <h6 class="dropdown-header">Change Status</h6>
                                            <form method="POST">
                                                <input type="hidden" name="action" value="toggle_status">
                                                <input type="hidden" name="client_id" value="<?php echo $c['id']; ?>">
                                                <?php if($c['access_status'] != 'active'): ?>
                                                <button type="submit" name="new_status" value="active" class="dropdown-item text-success">
                                                    <i class="fas fa-check mr-2"></i>Activate
                                                </button>
                                                <?php endif; ?>
                                                <?php if($c['access_status'] != 'suspended'): ?>
                                                <button type="submit" name="new_status" value="suspended" class="dropdown-item text-danger">
                                                    <i class="fas fa-ban mr-2"></i>Suspend
                                                </button>
                                                <?php endif; ?>
                                            </form>
                                            <div class="dropdown-divider"></div>
                                            <a href="#" class="dropdown-item" onclick="reassignClient(<?php echo $c['id']; ?>, '<?php echo htmlspecialchars($c['full_name']); ?>')">
                                                <i class="fas fa-exchange-alt mr-2"></i>Reassign Broker
                                            </a>
                                            <?php if($c['land_count'] == 0): ?>
                                            <form method="POST" onsubmit="return confirm('Delete this client?')">
                                                <input type="hidden" name="action" value="delete_client">
                                                <input type="hidden" name="client_id" value="<?php echo $c['id']; ?>">
                                                <button type="submit" class="dropdown-item text-danger">
                                                    <i class="fas fa-trash mr-2"></i>Delete
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <!-- Reassign Modal -->
    <div class="modal fade" id="reassignModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exchange-alt mr-2"></i>Reassign Client</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="reassign_broker">
                    <input type="hidden" name="client_id" id="reassign_client_id">
                    <div class="modal-body">
                        <p>Reassigning client: <strong id="reassign_client_name"></strong></p>
                        <div class="form-group">
                            <label>Select New Broker</label>
                            <select name="new_broker_id" class="form-control" required>
                                <option value="">-- Select Broker --</option>
                                <?php
                                mysqli_data_seek($brokers, 0);
                                while($b = mysqli_fetch_assoc($brokers)):
                                ?>
                                <option value="<?php echo $b['id']; ?>">
                                    <?php echo htmlspecialchars($b['full_name'] ?: $b['username']); ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Reassign</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
    /* Page-specific styles */
    .page-header {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

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

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

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

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

    .stat-icon.purple { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    .stat-icon.green { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }
    .stat-icon.red { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }

    .stat-info h3 {
        font-size: 24px;
        font-weight: 700;
        margin: 0;
        color: #1e293b;
    }

    .stat-info p {
        margin: 4px 0 0 0;
        color: #64748b;
        font-size: 14px;
    }

    .filter-card {
        background: white;
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 24px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
    }

    .filter-form {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        align-items: flex-end;
    }

    .filter-group {
        flex: 1;
        min-width: 150px;
    }

    .filter-group label {
        font-size: 12px;
        font-weight: 600;
        color: #64748b;
        margin-bottom: 6px;
        display: block;
    }

    .filter-group .form-control {
        border-radius: 10px;
        border: 2px solid #e2e8f0;
        padding: 10px 14px;
        font-size: 14px;
    }

    .filter-group .form-control:focus {
        border-color: #06b6d4;
        box-shadow: 0 0 0 4px rgba(6, 182, 212, 0.1);
    }

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

    .btn-filter {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 10px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-filter:hover {
        transform: translateY(-2px);
    }

    .btn-clear {
        background: #f1f5f9;
        color: #64748b;
        padding: 10px 20px;
        border-radius: 10px;
        text-decoration: none;
        font-weight: 600;
        transition: all 0.3s ease;
    }

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

    .content-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        overflow: hidden;
    }

    .card-header-custom {
        padding: 24px 30px;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .card-header-custom h3 {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #1e293b;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .result-count {
        background: #f1f5f9;
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 13px;
        color: #64748b;
        font-weight: 500;
    }

    .card-body { padding: 0; }

    .modern-table { margin: 0; }

    .modern-table thead th {
        background: #f8fafc;
        border: none;
        padding: 16px 20px;
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
    }

    .modern-table tbody td {
        padding: 16px 20px;
        border-bottom: 1px solid #f1f5f9;
        vertical-align: middle;
    }

    .modern-table tbody tr:hover { background: #f8fafc; }

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

    .client-avatar {
        width: 42px;
        height: 42px;
        border-radius: 12px;
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 600;
        font-size: 16px;
    }

    .client-info {
        display: flex;
        flex-direction: column;
    }

    .client-info strong { font-size: 14px; color: #1e293b; }
    .client-info span { font-size: 12px; color: #94a3b8; }

    .contact-cell {
        display: flex;
        flex-direction: column;
    }

    .contact-cell .phone { font-size: 13px; color: #1e293b; }
    .contact-cell .email { font-size: 12px; color: #94a3b8; }

    .land-count {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        background: #f1f5f9;
        border-radius: 8px;
        font-weight: 600;
        color: #475569;
    }

    .payment-badge {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 10px;
        border-radius: 8px;
        font-size: 11px;
        font-weight: 600;
    }

    .payment-badge.paid {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.15) 0%, rgba(22, 163, 74, 0.15) 100%);
        color: #16a34a;
    }

    .payment-badge.unpaid {
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.15) 0%, rgba(220, 38, 38, 0.15) 100%);
        color: #dc2626;
    }

    .total-paid {
        display: block;
        font-size: 11px;
        color: #64748b;
        margin-top: 4px;
    }

    .status-badge {
        display: inline-block;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .status-active {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        color: white;
    }

    .status-suspended {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: white;
    }

    .status-expired {
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        color: white;
    }

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

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

    .dropdown-menu {
        border: none;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.12);
        padding: 8px;
    }

    .dropdown-item {
        border-radius: 8px;
        padding: 10px 16px;
        font-size: 14px;
    }

    .dropdown-item:hover { background: #f8fafc; }

    .modal-content {
        border: none;
        border-radius: 20px;
    }

    .modal-header {
        border-bottom: 1px solid #f1f5f9;
        padding: 20px 24px;
    }

    .modal-body { padding: 24px; }
    .modal-footer {
        border-top: 1px solid #f1f5f9;
        padding: 16px 24px;
    }

    .btn {
        border-radius: 10px;
        padding: 10px 20px;
        font-weight: 600;
    }

    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }

    .alert {
        border: none;
        border-radius: 14px;
        padding: 16px 20px;
        margin-bottom: 25px;
    }

    .alert-success {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(22, 163, 74, 0.1) 100%);
        color: #166534;
        border-left: 4px solid #22c55e;
    }

    .alert-danger {
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(220, 38, 38, 0.1) 100%);
        color: #991b1b;
        border-left: 4px solid #ef4444;
    }

    @media (max-width: 768px) {
        .page-header { padding: 20px; }
        .page-title h1 { font-size: 22px; }
        .filter-form { flex-direction: column; }
        .filter-group { min-width: 100%; }
        .filter-actions { width: 100%; }
        .card-header-custom {
            padding: 16px 20px;
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;
        }
    }
    </style>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function reassignClient(id, name) {
            document.getElementById('reassign_client_id').value = id;
            document.getElementById('reassign_client_name').textContent = name;
            $('#reassignModal').modal('show');
        }
    </script>
</body>
</html>
