<?php
/**
 * Policy Reports
 * Generate policy reports
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_policy_reports');

$product_id = $_GET['product_id'] ?? '';
$status = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-01-01');
$date_to = $_GET['date_to'] ?? date('Y-m-t');

$where = ["1=1"];
$params = [];
$types = '';

if ($product_id) {
    $where[] = "lp.product_id = ?";
    $params[] = $product_id;
    $types .= 'i';
}

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

$where[] = "DATE(lp.created_at) BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';

$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);
$total_sum_assured = array_sum(array_column($policies, 'sum_assured'));
$total_premiums = array_sum(array_column($policies, 'premium_amount'));

$products = $conn->query("SELECT product_id, product_name FROM life_insurance_products WHERE is_active = 1")->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'Policy Reports';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Policy Reports')); ?>
    <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>Policy Reports</h2>
                                <p>Generate comprehensive policy reports</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">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 class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Premiums</h6>
                                <span class="metric-icon"><i class="ri-bank-card-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_premiums, 0); ?></div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <select name="product_id" class="form-select" style="width: auto;">
                                    <option value="">All Products</option>
                                    <?php foreach ($products as $prod): ?>
                                        <option value="<?php echo $prod['product_id']; ?>" <?php echo $product_id == $prod['product_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($prod['product_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <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>
                                <input type="date" name="date_from" class="form-control" style="width: auto;" value="<?php echo $date_from; ?>">
                                <input type="date" name="date_to" class="form-control" style="width: auto;" value="<?php echo $date_to; ?>">
                                <button type="submit" class="btn btn-primary">Filter</button>
                                <button type="button" onclick="window.print()" class="btn btn-success">
                                    <i class="ri-printer-line me-2"></i>Print
                                </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">Policy Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Policy Number</th>
                                                    <th>Member</th>
                                                    <th>Product</th>
                                                    <th>Sum Assured</th>
                                                    <th>Premium</th>
                                                    <th>Status</th>
                                                    <th>Start Date</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($policies)): ?>
                                                    <tr><td colspan="7" 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>
                                                        </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>
