<?php
/**
 * Agent Policies
 * View policies 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'];
$status = $_GET['status'] ?? '';

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

if ($status) {
    $where[] = "lp.policy_status = ?";
    $params[] = $status;
    $types .= 's';
}

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

$sql = "SELECT lp.*, m.member_number, m.first_name, m.last_name, lip.product_name, lip.product_type
        FROM life_policies lp
        INNER JOIN members m ON lp.member_id = m.member_id
        LEFT JOIN life_insurance_products lip ON lp.product_id = lip.product_id
        WHERE $whereClause
        ORDER BY lp.created_at DESC";

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

// Calculate statistics
$total_policies = count($policies);
$active_policies = count(array_filter($policies, function($p) { return $p['policy_status'] === 'ACTIVE'; }));
$total_sum_assured = array_sum(array_column($policies, 'sum_assured'));

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Policies')); ?>
    <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 Policies</h2>
                                <p>View policies you've sold</p>
                            </div>
                        </div>
                    </div>

                    <div class="metrics-row">
                        <div class="metric-card policies">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Policies</h6>
                                <span class="metric-icon"><i class="ri-file-shield-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $total_policies; ?></div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Active Policies</h6>
                                <span class="metric-icon"><i class="ri-check-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $active_policies; ?></div>
                        </div>

                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Sum Assured</h6>
                                <span class="metric-icon"><i class="ri-money-dollar-circle-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_sum_assured, 0); ?></div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="policies.php?action=create" class="btn btn-primary">
                                <i class="ri-file-add-line me-2"></i>New Policy
                            </a>
                            <form method="GET" class="d-inline-flex gap-2 ms-2">
                                <select name="status" class="form-select" style="width: auto;">
                                    <option value="">All Status</option>
                                    <option value="ACTIVE" <?php echo $status === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                    <option value="LAPSED" <?php echo $status === 'LAPSED' ? 'selected' : ''; ?>>Lapsed</option>
                                    <option value="SURRENDERED" <?php echo $status === 'SURRENDERED' ? 'selected' : ''; ?>>Surrendered</option>
                                </select>
                                <button type="submit" class="btn btn-secondary">Filter</button>
                            </form>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Policies List</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Policy Number</th>
                                                    <th>Client</th>
                                                    <th>Product</th>
                                                    <th>Sum Assured</th>
                                                    <th>Premium</th>
                                                    <th>Status</th>
                                                    <th>Start Date</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($policies)): ?>
                                                    <tr><td colspan="8" class="text-center">No policies found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($policies as $policy): ?>
                                                        <tr>
                                                            <td><strong><?php echo htmlspecialchars($policy['policy_number']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($policy['member_number'] . ' - ' . $policy['first_name'] . ' ' . $policy['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($policy['product_name'] ?? 'N/A'); ?></td>
                                                            <td>KES <?php echo number_format($policy['sum_assured'], 2); ?></td>
                                                            <td>KES <?php echo number_format($policy['premium_amount'], 2); ?></td>
                                                            <td><span class="status-badge status-<?php echo strtolower($policy['policy_status']); ?>"><?php echo htmlspecialchars($policy['policy_status']); ?></span></td>
                                                            <td><?php echo date('d M Y', strtotime($policy['policy_start_date'])); ?></td>
                                                            <td>
                                                                <a href="policy_details.php?id=<?php echo $policy['policy_id']; ?>" class="btn btn-sm btn-info">
                                                                    <i class="ri-eye-line"></i>
                                                                </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>
