<?php
/**
 * Bonus Reports
 * Generate bonus allocation reports
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_bonus_reports');

$product_id = $_GET['product_id'] ?? '';
$year = $_GET['year'] ?? date('Y');

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

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

if ($year) {
    $where[] = "YEAR(b.allocation_date) = ?";
    $params[] = $year;
    $types .= 'i';
}

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

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

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

// Calculate totals
$total_bonuses = array_sum(array_column($bonuses, 'bonus_amount'));

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Bonus 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, #f59e0b 0%, #d97706 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Bonus Reports</h2>
                                <p>Generate bonus allocation reports</p>
                            </div>
                        </div>
                    </div>

                    <div class="metrics-row">
                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Bonuses</h6>
                                <span class="metric-icon"><i class="ri-gift-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_bonuses, 0); ?></div>
                            <div class="metric-change">Period total</div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Allocations</h6>
                                <span class="metric-icon"><i class="ri-file-list-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo count($bonuses); ?></div>
                            <div class="metric-change">Total allocations</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>
                                <input type="number" name="year" class="form-control" style="width: 120px;" value="<?php echo $year; ?>" placeholder="Year">
                                <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">Bonus Allocations</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Allocation Date</th>
                                                    <th>Policy</th>
                                                    <th>Member</th>
                                                    <th>Product</th>
                                                    <th>Bonus Amount</th>
                                                    <th>Type</th>
                                                    <th>Policy Year</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($bonuses)): ?>
                                                    <tr><td colspan="7" class="text-center">No bonuses found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($bonuses as $bonus): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y', strtotime($bonus['allocation_date'])); ?></td>
                                                            <td><strong><?php echo htmlspecialchars($bonus['policy_number']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($bonus['member_number'] . ' - ' . $bonus['first_name'] . ' ' . $bonus['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($bonus['product_name'] ?? 'N/A'); ?></td>
                                                            <td><strong>KES <?php echo number_format($bonus['bonus_amount'], 2); ?></strong></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($bonus['bonus_type'] ?? 'REVERSIONARY'); ?></span></td>
                                                            <td><?php echo $bonus['policy_year'] ?? '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>
