<?php
/**
 * Policy Rules
 * Configure life insurance policy calculation rules
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('manage_policy_rules');

$product_id = $_GET['product_id'] ?? null;
$message = '';
$messageType = '';

if (!$product_id) {
    header('Location: policy_products.php');
    exit();
}

// Get product details
$product = $conn->query("SELECT * FROM life_insurance_products WHERE product_id = $product_id")->fetch_assoc();

if (!$product) {
    header('Location: policy_products.php');
    exit();
}

// Get policy rules for this product
$rules = $conn->query("SELECT * FROM policy_rules WHERE product_id = $product_id ORDER BY rule_type, policy_year")->fetch_all(MYSQLI_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rule_type = $_POST['rule_type'];
    $policy_year = $_POST['policy_year'] ?? null;
    $rule_value = $_POST['rule_value'];
    $description = $_POST['description'] ?? null;
    
    // Check if rule exists
    $check = $conn->query("SELECT * FROM policy_rules 
                          WHERE product_id = $product_id AND rule_type = '$rule_type' 
                          AND ($policy_year IS NULL OR policy_year = $policy_year)")->fetch_assoc();
    
    if ($check) {
        // Update
        $sql = "UPDATE policy_rules SET rule_value = ?, description = ? 
                WHERE rule_id = {$check['rule_id']}";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $rule_value, $description);
    } else {
        // Insert
        $sql = "INSERT INTO policy_rules (product_id, rule_type, policy_year, rule_value, description)
                VALUES (?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isiss", $product_id, $rule_type, $policy_year, $rule_value, $description);
    }
    
    if ($stmt->execute()) {
        $message = 'Policy rule saved successfully';
        $messageType = 'success';
        // Refresh rules
        $rules = $conn->query("SELECT * FROM policy_rules WHERE product_id = $product_id ORDER BY rule_type, policy_year")->fetch_all(MYSQLI_ASSOC);
    } else {
        $message = 'Failed to save policy rule';
        $messageType = 'danger';
    }
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Policy 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">
                    <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>Policy Rules Configuration</h2>
                                <p><?php echo htmlspecialchars($product['product_name']); ?> - Calculation Rules</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-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Add/Edit Rule</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Rule Type <span class="text-danger">*</span></label>
                                            <select name="rule_type" class="form-select" required>
                                                <option value="">Select Type</option>
                                                <option value="SURRENDER_FACTOR">Surrender Factor</option>
                                                <option value="BONUS_RATE">Bonus Rate</option>
                                                <option value="DEATH_BENEFIT_MULTIPLIER">Death Benefit Multiplier</option>
                                                <option value="MATURITY_BENEFIT_MULTIPLIER">Maturity Benefit Multiplier</option>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Policy Year</label>
                                            <input type="number" name="policy_year" class="form-control" min="1" 
                                                   placeholder="Leave blank for all years">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Rule Value <span class="text-danger">*</span></label>
                                            <input type="number" name="rule_value" class="form-control" step="0.01" required>
                                            <small class="text-muted">Percentage or multiplier value</small>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Description</label>
                                            <textarea name="description" class="form-control" rows="2"></textarea>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-2"></i>Save Rule
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Current Rules</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Type</th>
                                                    <th>Policy Year</th>
                                                    <th>Value</th>
                                                    <th>Description</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($rules)): ?>
                                                    <tr><td colspan="4" class="text-center">No rules configured</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($rules as $rule): ?>
                                                        <tr>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($rule['rule_type']); ?></span></td>
                                                            <td><?php echo $rule['policy_year'] ? $rule['policy_year'] : 'All'; ?></td>
                                                            <td><strong><?php echo number_format($rule['rule_value'], 2); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($rule['description'] ?? 'N/A'); ?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-12">
                            <a href="policy_products.php" class="btn btn-secondary">
                                <i class="ri-arrow-left-line me-2"></i>Back to Products
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
