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

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

requireLogin();
requirePermission('view_policies');

$lifeService = new LifeInsuranceService($conn);
$action = $_GET['action'] ?? 'list';
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'create') {
    $result = $lifeService->createPolicy($_POST);
    if ($result['success']) {
        $message = $result['message'];
        $messageType = 'success';
        $action = 'list';
    } else {
        $message = $result['message'];
        $messageType = 'danger';
    }
}

// Get filters
$filters = [
    'product_id' => $_GET['product_id'] ?? '',
    'status' => $_GET['status'] ?? '',
    'search' => $_GET['search'] ?? ''
];

$page = $_GET['page'] ?? 1;
$perPage = 20;

// Get policies
$policiesData = $lifeService->getPolicies($filters, $page, $perPage);
$policies = $policiesData['policies'];
$pagination = $policiesData['pagination'];

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

$pageTitle = 'Life Insurance Policies';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Life Insurance Policies')); ?>
    <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, #ec4899 0%, #db2777 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Life Insurance Policies</h2>
                                <p>Manage life insurance policies and products</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="policies.php?action=create" class="btn btn-primary">
                                <i class="ri-file-shield-line me-2"></i>Add New Policy
                            </a>
                            <a href="policy_products.php" class="btn btn-success">
                                <i class="ri-product-hunt-line me-2"></i>Policy Products
                            </a>
                        </div>
                    </div>

                    <?php if ($action === 'create'): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Add New Policy</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Policy Number <span class="text-danger">*</span></label>
                                                    <input type="text" name="policy_number" class="form-control" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Product <span class="text-danger">*</span></label>
                                                    <select name="product_id" class="form-select" required>
                                                        <option value="">Select Product</option>
                                                        <?php foreach ($products as $product): ?>
                                                            <option value="<?php echo $product['product_id']; ?>">
                                                                <?php echo htmlspecialchars($product['product_name'] . ' (' . $product['product_type'] . ')'); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Sum Assured (KES) <span class="text-danger">*</span></label>
                                                    <input type="number" name="sum_assured" class="form-control" step="0.01" required>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Premium Amount (KES) <span class="text-danger">*</span></label>
                                                    <input type="number" name="premium_amount" class="form-control" step="0.01" required>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Premium Frequency</label>
                                                    <select name="premium_frequency" class="form-select">
                                                        <option value="MONTHLY">Monthly</option>
                                                        <option value="QUARTERLY">Quarterly</option>
                                                        <option value="SEMI_ANNUAL">Semi-Annual</option>
                                                        <option value="ANNUAL" selected>Annual</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Policy Start Date <span class="text-danger">*</span></label>
                                                    <input type="date" name="policy_start_date" class="form-control" required>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Policy End Date</label>
                                                    <input type="date" name="policy_end_date" class="form-control">
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Maturity Date</label>
                                                    <input type="date" name="maturity_date" class="form-control">
                                                </div>
                                            </div>
                                            <button type="submit" class="btn btn-primary">Create Policy</button>
                                            <a href="policies.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title">Policies List</h4>
                                    </div>
                                    <div class="card-body">
                                        <form method="GET" class="mb-3">
                                            <div class="row">
                                                <div class="col-md-4 mb-2">
                                                    <input type="text" name="search" class="form-control" placeholder="Search..." value="<?php echo htmlspecialchars($filters['search']); ?>">
                                                </div>
                                                <div class="col-md-3 mb-2">
                                                    <select name="status" class="form-select">
                                                        <option value="">All Status</option>
                                                        <option value="ACTIVE" <?php echo $filters['status'] === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                        <option value="LAPSED" <?php echo $filters['status'] === 'LAPSED' ? 'selected' : ''; ?>>Lapsed</option>
                                                        <option value="MATURED" <?php echo $filters['status'] === 'MATURED' ? 'selected' : ''; ?>>Matured</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                                                </div>
                                            </div>
                                        </form>
                                        
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Policy Number</th>
                                                        <th>Product</th>
                                                        <th>Member</th>
                                                        <th>Sum Assured</th>
                                                        <th>Premium</th>
                                                        <th>Status</th>
                                                        <th>Actions</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><?php echo htmlspecialchars($policy['policy_number']); ?></td>
                                                                <td><?php echo htmlspecialchars($policy['product_name'] ?? 'N/A'); ?></td>
                                                                <td><?php echo htmlspecialchars($policy['member_number'] ? $policy['member_number'] . ' - ' . $policy['first_name'] . ' ' . $policy['last_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="badge bg-<?php 
                                                                        echo $policy['policy_status'] === 'ACTIVE' ? 'success' : 
                                                                             ($policy['policy_status'] === 'LAPSED' ? 'danger' : 'info'); 
                                                                    ?>">
                                                                        <?php echo htmlspecialchars($policy['policy_status']); ?>
                                                                    </span>
                                                                </td>
                                                                <td>
                                                                    <a href="policy_details.php?id=<?php echo $policy['policy_id']; ?>" class="btn btn-sm btn-info">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
