<?php
/**
 * Premiums Management
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_premiums');

$action = $_GET['action'] ?? 'list';
$status = $_GET['status'] ?? '';

// Build query
$where = ["1=1"];
$params = [];
$types = '';

if (!empty($status)) {
    $where[] = "p.payment_status = ?";
    $params[] = $status;
    $types .= 's';
}

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

$sql = "SELECT p.*, lp.policy_number, m.member_number, m.first_name, m.last_name
        FROM premiums p
        INNER JOIN life_policies lp ON p.policy_id = lp.policy_id
        LEFT JOIN members m ON lp.member_id = m.member_id
        WHERE $whereClause
        ORDER BY p.premium_due_date DESC, p.created_at DESC
        LIMIT 50";

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Premiums Management')); ?>
    <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">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Premiums Management</h2>
                                <p>Manage life insurance premium payments</p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="premiums.php?action=create" class="btn btn-primary">
                                <i class="ri-bank-card-line me-2"></i>Post Premium
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Premiums List</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="mb-3">
                                        <a href="premiums.php" class="btn btn-sm <?php echo empty($status) ? 'btn-primary' : 'btn-outline-primary'; ?>">All</a>
                                        <a href="premiums.php?status=PENDING" class="btn btn-sm <?php echo $status === 'PENDING' ? 'btn-warning' : 'btn-outline-warning'; ?>">Pending</a>
                                        <a href="premiums.php?status=PAID" class="btn btn-sm <?php echo $status === 'PAID' ? 'btn-success' : 'btn-outline-success'; ?>">Paid</a>
                                        <a href="premiums.php?status=OVERDUE" class="btn btn-sm <?php echo $status === 'OVERDUE' ? 'btn-danger' : 'btn-outline-danger'; ?>">Overdue</a>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Due Date</th>
                                                    <th>Policy Number</th>
                                                    <th>Member</th>
                                                    <th>Premium Amount</th>
                                                    <th>Status</th>
                                                    <th>Paid Date</th>
                                                    <th>Actions</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><?php echo htmlspecialchars($premium['policy_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($premium['member_number'] ? $premium['member_number'] . ' - ' . $premium['first_name'] . ' ' . $premium['last_name'] : 'N/A'); ?></td>
                                                            <td>KES <?php echo number_format($premium['premium_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="badge bg-<?php 
                                                                    echo $premium['payment_status'] === 'PAID' ? 'success' : 
                                                                         ($premium['payment_status'] === 'OVERDUE' ? 'danger' : 'warning'); 
                                                                ?>">
                                                                    <?php echo htmlspecialchars($premium['payment_status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $premium['paid_date'] ? date('d M Y', strtotime($premium['paid_date'])) : 'N/A'; ?></td>
                                                            <td>
                                                                <a href="premium_details.php?id=<?php echo $premium['premium_id']; ?>" class="btn btn-sm btn-info" title="View Details">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                                <?php if ($premium['payment_status'] === 'PAID'): ?>
                                                                    <button onclick="generateETIMSInvoice(<?php echo $premium['premium_id']; ?>, 'PREMIUM')" class="btn btn-sm btn-warning" title="Generate eTIMS Invoice">
                                                                        <i class="ri-file-invoice-line"></i>
                                                                    </button>
                                                                <?php endif; ?>
                                                                <?php if ($premium['payment_status'] === 'PENDING'): ?>
                                                                    <a href="mark_premium_paid.php?id=<?php echo $premium['premium_id']; ?>" class="btn btn-sm btn-success" title="Mark as Paid">
                                                                        <i class="ri-check-line"></i>
                                                                    </a>
                                                                <?php endif; ?>
                                                            </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'; ?>
    <script>
    function generateETIMSInvoice(sourceId, sourceType) {
        if (!confirm('Generate eTIMS invoice for this ' + sourceType.toLowerCase() + '?')) {
            return;
        }
        
        $.ajax({
            url: 'ajax/generate_etims_invoice.php',
            method: 'POST',
            data: {
                source_id: sourceId,
                source_type: sourceType
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert('eTIMS invoice generated successfully!\nInvoice Number: ' + (response.invoice_number || 'N/A'));
                    location.reload();
                } else {
                    alert('Error: ' + (response.message || 'Failed to generate invoice'));
                }
            },
            error: function() {
                alert('Error generating invoice. Please try again.');
            }
        });
    }
    </script>
</body>
</html>
