<?php
/**
 * Allocate Bonus
 * Allocate bonuses to life insurance policies
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('allocate_bonuses');

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $policy_id = $_POST['policy_id'];
    $bonus_amount = $_POST['bonus_amount'];
    $bonus_type = $_POST['bonus_type'] ?? 'REVERSIONARY';
    $allocation_date = $_POST['allocation_date'] ?? date('Y-m-d');
    
    // Get policy year
    $policy = $conn->query("SELECT policy_start_date FROM life_policies WHERE policy_id = $policy_id")->fetch_assoc();
    $policy_start = new DateTime($policy['policy_start_date']);
    $allocation = new DateTime($allocation_date);
    $policy_year = $policy_start->diff($allocation)->y + 1;
    
    $sql = "INSERT INTO bonuses (policy_id, bonus_amount, bonus_type, allocation_date, policy_year, created_by)
            VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $created_by = $_SESSION['user_id'];
    $stmt->bind_param("idssii", $policy_id, $bonus_amount, $bonus_type, $allocation_date, $policy_year, $created_by);
    
    if ($stmt->execute()) {
        // Update policy accumulated bonuses
        $updateSql = "UPDATE life_policies SET 
                     accumulated_bonuses = COALESCE(accumulated_bonuses, 0) + ?
                     WHERE policy_id = ?";
        $updateStmt = $conn->prepare($updateSql);
        $updateStmt->bind_param("di", $bonus_amount, $policy_id);
        $updateStmt->execute();
        
        $message = 'Bonus allocated successfully';
        $messageType = 'success';
    } else {
        $message = 'Failed to allocate bonus';
        $messageType = 'danger';
    }
}

// Get active policies
$policies = $conn->query("SELECT lp.policy_id, lp.policy_number, m.member_number, m.first_name, m.last_name
                         FROM life_policies lp
                         INNER JOIN members m ON lp.member_id = m.member_id
                         WHERE lp.policy_status = 'ACTIVE'
                         ORDER BY lp.policy_number")->fetch_all(MYSQLI_ASSOC);

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Allocate Bonus')); ?>
    <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>Allocate Bonus</h2>
                                <p>Allocate bonuses to life insurance policies</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">
                        <div class="col-md-8">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Bonus Allocation Form</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Policy <span class="text-danger">*</span></label>
                                            <select name="policy_id" class="form-select" required>
                                                <option value="">Select Policy</option>
                                                <?php foreach ($policies as $policy): ?>
                                                    <option value="<?php echo $policy['policy_id']; ?>">
                                                        <?php echo htmlspecialchars($policy['policy_number'] . ' - ' . $policy['member_number'] . ' - ' . $policy['first_name'] . ' ' . $policy['last_name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Bonus Amount (KES) <span class="text-danger">*</span></label>
                                                <input type="number" name="bonus_amount" class="form-control" 
                                                       step="0.01" min="0" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Bonus Type</label>
                                                <select name="bonus_type" class="form-select">
                                                    <option value="REVERSIONARY">Reversionary</option>
                                                    <option value="TERMINAL">Terminal</option>
                                                    <option value="INTERIM">Interim</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Allocation Date</label>
                                            <input type="date" name="allocation_date" class="form-control" 
                                                   value="<?php echo date('Y-m-d'); ?>">
                                        </div>
                                        
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            The bonus will be added to the policy's accumulated bonuses and will be included in death/maturity benefit calculations.
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-2"></i>Allocate Bonus
                                        </button>
                                        <a href="bonuses.php" class="btn btn-secondary">Cancel</a>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
