<?php
/**
 * Premium Reports
 * Generate premium payment reports
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_premium_reports');

$product_id = $_GET['product_id'] ?? '';
$status = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01', strtotime('-12 months'));
$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[] = "pr.payment_status = ?";
    $params[] = $status;
    $types .= 's';
}

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

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

$sql = "SELECT pr.*, lp.policy_number, m.member_number, m.first_name, m.last_name, lip.product_name
        FROM premiums pr
        INNER JOIN life_policies lp ON pr.policy_id = lp.policy_id
        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 pr.premium_due_date DESC";

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

// Calculate totals
$total_due = array_sum(array_column($premiums, 'premium_amount'));
$total_paid = array_sum(array_filter(array_column($premiums, 'premium_amount'), function($v, $k) use ($premiums) {
    return $premiums[$k]['payment_status'] === 'PAID';
}, ARRAY_FILTER_USE_BOTH));

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Premium 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>Premium Reports</h2>
                                <p>Generate premium payment reports</p>
                            </div>
                        </div>
                    </div>

                    <div class="metrics-row">
                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Due</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_due, 0); ?></div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Paid</h6>
                                <span class="metric-icon"><i class="ri-check-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_paid, 0); ?></div>
                        </div>

                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Outstanding</h6>
                                <span class="metric-icon"><i class="ri-time-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_due - $total_paid, 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="PAID" <?php echo $status === 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                    <option value="PENDING" <?php echo $status === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="OVERDUE" <?php echo $status === 'OVERDUE' ? 'selected' : ''; ?>>Overdue</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">Premium Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Due Date</th>
                                                    <th>Policy</th>
                                                    <th>Member</th>
                                                    <th>Product</th>
                                                    <th>Amount (KES)</th>
                                                    <th>Status</th>
                                                    <th>Payment Date</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($premiums)): ?>
                                                    <tr><td colspan="7" class="text-center">No premiums found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($premiums as $premium): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y', strtotime($premium['premium_due_date'])); ?></td>
                                                            <td><strong><?php echo htmlspecialchars($premium['policy_number']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($premium['member_number'] . ' - ' . $premium['first_name'] . ' ' . $premium['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($premium['product_name'] ?? 'N/A'); ?></td>
                                                            <td><strong>KES <?php echo number_format($premium['premium_amount'], 2); ?></strong></td>
                                                            <td><span class="status-badge status-<?php echo strtolower($premium['payment_status']); ?>"><?php echo htmlspecialchars($premium['payment_status']); ?></span></td>
                                                            <td><?php echo $premium['payment_date'] ? date('d M Y', strtotime($premium['payment_date'])) : 'N/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>
