<?php
/**
 * Scheme Rules Management
 * Configure withdrawal rules and calculation formulas per scheme
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('manage_scheme_rules');

$scheme_id = $_GET['id'] ?? null;
$message = '';
$messageType = '';

if (!$scheme_id) {
    header('Location: schemes.php');
    exit();
}

// Get scheme details
$scheme = $conn->query("SELECT * FROM pension_schemes WHERE scheme_id = $scheme_id")->fetch_assoc();

if (!$scheme) {
    header('Location: schemes.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sql = "UPDATE pension_schemes SET 
            retirement_age = ?,
            early_exit_max_cash_percentage = ?,
            early_exit_balance_action = ?,
            retirement_commutation_percentage = ?,
            retirement_balance_action = ?,
            disability_full_withdrawal_allowed = ?,
            emigration_full_withdrawal_allowed = ?,
            investment_return_allocation_frequency = ?,
            updated_at = CURRENT_TIMESTAMP
            WHERE scheme_id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("idsdsiiisi",
        $_POST['retirement_age'],
        $_POST['early_exit_max_cash_percentage'],
        $_POST['early_exit_balance_action'],
        $_POST['retirement_commutation_percentage'] ?? null,
        $_POST['retirement_balance_action'],
        $_POST['disability_full_withdrawal_allowed'] ?? 1,
        $_POST['emigration_full_withdrawal_allowed'] ?? 1,
        $_POST['investment_return_allocation_frequency'],
        $scheme_id
    );
    
    if ($stmt->execute()) {
        $message = 'Scheme rules updated successfully';
        $messageType = 'success';
        // Refresh scheme data
        $scheme = $conn->query("SELECT * FROM pension_schemes WHERE scheme_id = $scheme_id")->fetch_assoc();
    } else {
        $message = 'Failed to update scheme rules';
        $messageType = 'danger';
    }
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Scheme Rules')); ?>
    <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, #10b981 0%, #059669 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Scheme Rules Configuration</h2>
                                <p><?php echo htmlspecialchars($scheme['scheme_name']); ?> - Withdrawal Rules & Calculation Formulas</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-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Withdrawal Rules & Calculation Formulas</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST">
                                        <div class="alert alert-info mb-4">
                                            <i class="ri-information-line me-2"></i>
                                            <strong>Note:</strong> These rules govern how withdrawals are calculated for this scheme. 
                                            Changes affect all future withdrawal calculations.
                                        </div>
                                        
                                        <h5 class="mb-3">Retirement Configuration</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Retirement Age <span class="text-danger">*</span></label>
                                                <input type="number" name="retirement_age" class="form-control" 
                                                       value="<?php echo $scheme['retirement_age']; ?>" required>
                                                <small class="text-muted">Standard retirement age for this scheme</small>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Commutation Percentage (%)</label>
                                                <input type="number" name="retirement_commutation_percentage" 
                                                       class="form-control" step="0.01" min="0" max="100"
                                                       value="<?php echo $scheme['retirement_commutation_percentage'] ?? ''; ?>">
                                                <small class="text-muted">Max % of accrued benefits as lump sum at retirement</small>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Retirement Balance Action</label>
                                                <select name="retirement_balance_action" class="form-select">
                                                    <option value="ANNUITY" <?php echo $scheme['retirement_balance_action'] === 'ANNUITY' ? 'selected' : ''; ?>>Annuity</option>
                                                    <option value="PROGRAMMED_WITHDRAWAL" <?php echo $scheme['retirement_balance_action'] === 'PROGRAMMED_WITHDRAWAL' ? 'selected' : ''; ?>>Programmed Withdrawal</option>
                                                    <option value="DEFER" <?php echo $scheme['retirement_balance_action'] === 'DEFER' ? 'selected' : ''; ?>>Defer</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">Early Exit Rules (Before Retirement Age)</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Maximum Cash Percentage (%) <span class="text-danger">*</span></label>
                                                <input type="number" name="early_exit_max_cash_percentage" 
                                                       class="form-control" step="0.01" min="0" max="100"
                                                       value="<?php echo $scheme['early_exit_max_cash_percentage']; ?>" required>
                                                <small class="text-muted">
                                                    Occupational/Umbrella: 50%, IPP: up to 100%
                                                </small>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Early Exit Balance Action</label>
                                                <select name="early_exit_balance_action" class="form-select">
                                                    <option value="DEFER" <?php echo $scheme['early_exit_balance_action'] === 'DEFER' ? 'selected' : ''; ?>>Defer</option>
                                                    <option value="TRANSFER" <?php echo $scheme['early_exit_balance_action'] === 'TRANSFER' ? 'selected' : ''; ?>>Transfer</option>
                                                    <option value="ANNUITY" <?php echo $scheme['early_exit_balance_action'] === 'ANNUITY' ? 'selected' : ''; ?>>Annuity</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">Special Withdrawal Conditions</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Disability Full Withdrawal</label>
                                                <select name="disability_full_withdrawal_allowed" class="form-select">
                                                    <option value="1" <?php echo $scheme['disability_full_withdrawal_allowed'] ? 'selected' : ''; ?>>Allowed (100%)</option>
                                                    <option value="0" <?php echo !$scheme['disability_full_withdrawal_allowed'] ? 'selected' : ''; ?>>Not Allowed</option>
                                                </select>
                                                <small class="text-muted">Whether permanent disability allows 100% withdrawal</small>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Emigration Full Withdrawal</label>
                                                <select name="emigration_full_withdrawal_allowed" class="form-select">
                                                    <option value="1" <?php echo $scheme['emigration_full_withdrawal_allowed'] ? 'selected' : ''; ?>>Allowed (100%)</option>
                                                    <option value="0" <?php echo !$scheme['emigration_full_withdrawal_allowed'] ? 'selected' : ''; ?>>Not Allowed</option>
                                                </select>
                                                <small class="text-muted">Whether permanent emigration allows 100% withdrawal</small>
                                            </div>
                                        </div>
                                        
                                        <hr class="my-4">
                                        
                                        <h5 class="mb-3">Investment Return Allocation</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Allocation Frequency</label>
                                                <select name="investment_return_allocation_frequency" class="form-select">
                                                    <option value="MONTHLY" <?php echo $scheme['investment_return_allocation_frequency'] === 'MONTHLY' ? 'selected' : ''; ?>>Monthly</option>
                                                    <option value="QUARTERLY" <?php echo $scheme['investment_return_allocation_frequency'] === 'QUARTERLY' ? 'selected' : ''; ?>>Quarterly</option>
                                                    <option value="ANNUALLY" <?php echo $scheme['investment_return_allocation_frequency'] === 'ANNUALLY' ? 'selected' : ''; ?>>Annually</option>
                                                </select>
                                                <small class="text-muted">How often investment returns are allocated to member accounts</small>
                                            </div>
                                        </div>
                                        
                                        <div class="alert alert-warning mt-4">
                                            <i class="ri-alert-line me-2"></i>
                                            <strong>Warning:</strong> Changing these rules will affect all future withdrawal calculations. 
                                            Ensure compliance with RBA regulations and scheme trust deed.
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-2"></i>Save Scheme Rules
                                        </button>
                                        <a href="schemes.php" class="btn btn-secondary">Back to Schemes</a>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
