<?php
/**
 * Claims Reports
 * Generate claims reports
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_claims_reports');

$claim_type = $_GET['claim_type'] ?? '';
$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 ($claim_type) {
    $where[] = "lc.claim_type = ?";
    $params[] = $claim_type;
    $types .= 's';
}

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

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

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

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

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

// Calculate totals
$total_claims = count($claims);
$total_claimed = array_sum(array_column($claims, 'claim_amount'));
$total_paid = array_sum(array_filter(array_column($claims, 'claim_amount'), function($v, $k) use ($claims) {
    return $claims[$k]['claim_status'] === 'PAID';
}, ARRAY_FILTER_USE_BOTH));

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

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

                    <div class="metrics-row">
                        <div class="metric-card claims">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Claims</h6>
                                <span class="metric-icon"><i class="ri-file-list-3-line"></i></span>
                            </div>
                            <div class="metric-value"><?php echo $total_claims; ?></div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Claimed</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_claimed, 0); ?></div>
                        </div>

                        <div class="metric-card withdrawals">
                            <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>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <select name="claim_type" class="form-select" style="width: auto;">
                                    <option value="">All Types</option>
                                    <option value="DEATH" <?php echo $claim_type === 'DEATH' ? 'selected' : ''; ?>>Death</option>
                                    <option value="MATURITY" <?php echo $claim_type === 'MATURITY' ? 'selected' : ''; ?>>Maturity</option>
                                    <option value="DISABILITY" <?php echo $claim_type === 'DISABILITY' ? 'selected' : ''; ?>>Disability</option>
                                </select>
                                <select name="status" class="form-select" style="width: auto;">
                                    <option value="">All Status</option>
                                    <option value="PENDING" <?php echo $status === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="APPROVED" <?php echo $status === 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                    <option value="PAID" <?php echo $status === 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                    <option value="REJECTED" <?php echo $status === 'REJECTED' ? 'selected' : ''; ?>>Rejected</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">Claims Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Submitted Date</th>
                                                    <th>Policy</th>
                                                    <th>Member</th>
                                                    <th>Type</th>
                                                    <th>Claim Amount</th>
                                                    <th>Status</th>
                                                    <th>Paid Date</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($claims)): ?>
                                                    <tr><td colspan="7" class="text-center">No claims found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($claims as $claim): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y', strtotime($claim['submitted_date'])); ?></td>
                                                            <td><strong><?php echo htmlspecialchars($claim['policy_number']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($claim['member_number'] . ' - ' . $claim['first_name'] . ' ' . $claim['last_name']); ?></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($claim['claim_type']); ?></span></td>
                                                            <td><strong>KES <?php echo number_format($claim['claim_amount'], 2); ?></strong></td>
                                                            <td><span class="status-badge status-<?php echo strtolower($claim['claim_status']); ?>"><?php echo htmlspecialchars($claim['claim_status']); ?></span></td>
                                                            <td><?php echo $claim['paid_date'] ? date('d M Y', strtotime($claim['paid_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>
