<?php
/**
 * Agent Clients
 * View clients managed by agent
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
if (!isAgent()) {
    header('Location: access_denied.php');
    exit();
}

$agent_id = $_SESSION['user_id'];
$search = $_GET['search'] ?? '';

$where = ["lp.agent_id = $agent_id"];
$params = [];
$types = '';

if ($search) {
    $where[] = "(m.member_number LIKE ? OR m.first_name LIKE ? OR m.last_name LIKE ? OR lp.policy_number LIKE ?)";
    $searchTerm = '%' . $search . '%';
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= 'ssss';
}

$whereClause = implode(' AND ', $where);

// Get unique clients (members) with their policy counts
$sql = "SELECT m.member_id, m.member_number, m.first_name, m.last_name, m.email, m.phone_number,
               COUNT(lp.policy_id) as policy_count,
               SUM(CASE WHEN lp.policy_status = 'ACTIVE' THEN 1 ELSE 0 END) as active_policies
        FROM members m
        INNER JOIN life_policies lp ON m.member_id = lp.member_id
        WHERE $whereClause
        GROUP BY m.member_id, m.member_number, m.first_name, m.last_name, m.email, m.phone_number
        ORDER BY m.member_number";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$clients = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'My Clients';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Clients')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #ec4899 0%, #db2777 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>My Clients</h2>
                                <p>View your client list and their policies</p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <input type="text" name="search" class="form-control" style="width: 300px;" 
                                       placeholder="Search by name, member number, or policy number..." 
                                       value="<?php echo htmlspecialchars($search); ?>">
                                <button type="submit" class="btn btn-primary">Search</button>
                                <?php if ($search): ?>
                                    <a href="agent_clients.php" class="btn btn-secondary">Clear</a>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Clients List</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Member Number</th>
                                                    <th>Name</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Total Policies</th>
                                                    <th>Active Policies</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($clients)): ?>
                                                    <tr><td colspan="7" class="text-center">No clients found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($clients as $client): ?>
                                                        <tr>
                                                            <td><strong><?php echo htmlspecialchars($client['member_number']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($client['first_name'] . ' ' . $client['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($client['email'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($client['phone_number'] ?? 'N/A'); ?></td>
                                                            <td><span class="badge bg-info"><?php echo $client['policy_count']; ?></span></td>
                                                            <td><span class="badge bg-success"><?php echo $client['active_policies']; ?></span></td>
                                                            <td>
                                                                <a href="agent_policies.php?client_id=<?php echo $client['member_id']; ?>" class="btn btn-sm btn-primary">
                                                                    <i class="ri-file-shield-line me-1"></i>View Policies
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
