<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$role_name = $_SESSION['role_name'];

// Check permission
/*function hasPermission($permission) {
    global $conn, $user_id;
    $sql = "SELECT HasPermission(?, ?) as has_permission";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("is", $user_id, $permission);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    return $result['has_permission'];
}
*/

$success_message = '';
$error_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $conn->begin_transaction();
        
        // Get form data
        $quote_id = $_POST['quote_id'] ?? null;
        $customer_id = $_POST['customer_id'];
        $product_id = $_POST['product_id'];
        $company_id = $_POST['company_id'];
        $agent_id = $_POST['agent_id'];
        $policy_type = $_POST['policy_type'];
        $coverage_type = $_POST['coverage_type'];
        $sum_assured = $_POST['sum_assured'];
        $premium_amount = $_POST['premium_amount'];
        $premium_frequency = $_POST['premium_frequency'];
        $policy_term_months = $_POST['policy_term_months'];
        $inception_date = $_POST['inception_date'];
        $commission_rate = $_POST['commission_rate'];
        $policy_fee = $_POST['policy_fee'] ?? 0;
        $stamp_duty = $_POST['stamp_duty'] ?? 0;
        $covered_members = !empty($_POST['covered_members']) ? json_encode($_POST['covered_members']) : null;
        $special_conditions = $_POST['special_conditions'] ?? '';
        $exclusions = !empty($_POST['exclusions']) ? json_encode($_POST['exclusions']) : null;
        $benefits = !empty($_POST['benefits']) ? json_encode($_POST['benefits']) : null;
        
        // Calculate dates
        $expiry_date = date('Y-m-d', strtotime($inception_date . ' + ' . $policy_term_months . ' months'));
        $next_premium_due = date('Y-m-d', strtotime($inception_date . ' + 1 month'));
        $commission_amount = ($premium_amount * $commission_rate) / 100;
        
        // Generate policy number
        $policy_number = 'POL-' . date('Y') . '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        
        // Check if policy number exists
        $check_sql = "SELECT policy_id FROM policies WHERE policy_number = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("s", $policy_number);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            $policy_number = 'POL-' . date('Y') . '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        }
        
        // Insert policy
        $sql = "INSERT INTO policies (
            policy_number, customer_id, product_id, company_id, agent_id, 
            policy_type, coverage_type, sum_assured, premium_amount, premium_frequency,
            policy_term_months, inception_date, expiry_date, next_premium_due,
            commission_rate, commission_amount, policy_fee, stamp_duty,
            covered_members, special_conditions, exclusions, benefits, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("siiiissddsisssdddsssss", 
            $policy_number, $customer_id, $product_id, $company_id, $agent_id,
            $policy_type, $coverage_type, $sum_assured, $premium_amount, $premium_frequency,
            $policy_term_months, $inception_date, $expiry_date, $next_premium_due,
            $commission_rate, $commission_amount, $policy_fee, $stamp_duty,
            $covered_members, $special_conditions, $exclusions, $benefits
        );
        
        if ($stmt->execute()) {
            $policy_id = $conn->insert_id;
            
            // Update quote status if applicable
            if ($quote_id) {
                $update_quote_sql = "UPDATE quotes SET status = 'CONVERTED', converted_policy_id = ? WHERE quote_id = ?";
                $update_quote_stmt = $conn->prepare($update_quote_sql);
                $update_quote_stmt->bind_param("ii", $policy_id, $quote_id);
                $update_quote_stmt->execute();
            }
            
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) VALUES (?, 'CREATE', 'POLICY', ?, ?)";
            $log_stmt = $conn->prepare($log_sql);
            $log_data = json_encode(['policy_number' => $policy_number, 'customer_id' => $customer_id]);
            $log_stmt->bind_param("iis", $user_id, $policy_id, $log_data);
            $log_stmt->execute();
            
            $conn->commit();
            $success_message = "Policy {$policy_number} issued successfully!";
        } else {
            throw new Exception("Failed to create policy");
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "Error issuing policy: " . $e->getMessage();
    }
}

// Get customers
$customers_sql = "SELECT customer_id, customer_number, first_name, last_name, phone_primary FROM customers WHERE is_active = 1 ORDER BY first_name, last_name";
$customers_result = $conn->query($customers_sql);

// Get products
$products_sql = "SELECT p.product_id, p.product_name, p.coverage_type, c.category_name, ic.company_name 
                 FROM insurance_products p 
                 JOIN product_categories c ON p.category_id = c.category_id 
                 JOIN insurance_companies ic ON p.company_id = ic.company_id 
                 WHERE p.is_active = 1 ORDER BY p.product_name";
$products_result = $conn->query($products_sql);

// Get agents
$agents_sql = "SELECT user_id, full_name, agent_code FROM users WHERE agent_code IS NOT NULL AND status = 'ACTIVE' ORDER BY full_name";
$agents_result = $conn->query($agents_sql);

// Get insurance companies
$companies_sql = "SELECT company_id, company_name FROM insurance_companies WHERE is_active = 1 ORDER BY company_name";
$companies_result = $conn->query($companies_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Issue Policy')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Issue New Policy</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_policies.php">Policies</a></li>
                                        <li class="breadcrumb-item active">Issue Policy</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="ri-check-line me-2"></i><?php echo $success_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Policy Form -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-file-add-line me-2"></i>Policy Details
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" id="policyForm" novalidate>
                                        <div class="row">
                                            <!-- Customer Selection -->
                                            <div class="col-md-6 mb-3">
                                                <label for="customer_id" class="form-label">Customer <span class="text-danger">*</span></label>
                                                <select class="form-select" id="customer_id" name="customer_id" required>
                                                    <option value="">Select Customer</option>
                                                    <?php while ($customer = $customers_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $customer['customer_id']; ?>">
                                                            <?php echo $customer['customer_number']; ?> - 
                                                            <?php echo $customer['first_name'] . ' ' . $customer['last_name']; ?>
                                                            (<?php echo $customer['phone_primary']; ?>)
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                                <div class="invalid-feedback">Please select a customer.</div>
                                            </div>

                                            <!-- Product Selection -->
                                            <div class="col-md-6 mb-3">
                                                <label for="product_id" class="form-label">Insurance Product <span class="text-danger">*</span></label>
                                                <select class="form-select" id="product_id" name="product_id" required>
                                                    <option value="">Select Product</option>
                                                    <?php while ($product = $products_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $product['product_id']; ?>" 
                                                                data-coverage="<?php echo $product['coverage_type']; ?>">
                                                            <?php echo $product['product_name']; ?> 
                                                            (<?php echo $product['category_name']; ?> - <?php echo $product['company_name']; ?>)
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                                <div class="invalid-feedback">Please select a product.</div>
                                            </div>

                                            <!-- Insurance Company -->
                                            <div class="col-md-6 mb-3">
                                                <label for="company_id" class="form-label">Insurance Company <span class="text-danger">*</span></label>
                                                <select class="form-select" id="company_id" name="company_id" required>
                                                    <option value="">Select Company</option>
                                                    <?php while ($company = $companies_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $company['company_id']; ?>">
                                                            <?php echo $company['company_name']; ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                                <div class="invalid-feedback">Please select an insurance company.</div>
                                            </div>

                                            <!-- Agent -->
                                            <div class="col-md-6 mb-3">
                                                <label for="agent_id" class="form-label">Agent <span class="text-danger">*</span></label>
                                                <select class="form-select" id="agent_id" name="agent_id" required>
                                                    <option value="">Select Agent</option>
                                                    <?php while ($agent = $agents_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $agent['user_id']; ?>"
                                                                <?php echo ($agent['user_id'] == $user_id) ? 'selected' : ''; ?>>
                                                            <?php echo $agent['agent_code']; ?> - <?php echo $agent['full_name']; ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                                <div class="invalid-feedback">Please select an agent.</div>
                                            </div>

                                            <!-- Policy Type -->
                                            <div class="col-md-6 mb-3">
                                                <label for="policy_type" class="form-label">Policy Type <span class="text-danger">*</span></label>
                                                <select class="form-select" id="policy_type" name="policy_type" required>
                                                    <option value="">Select Type</option>
                                                    <option value="INDIVIDUAL">Individual</option>
                                                    <option value="FAMILY">Family</option>
                                                    <option value="GROUP">Group</option>
                                                    <option value="CORPORATE">Corporate</option>
                                                </select>
                                                <div class="invalid-feedback">Please select policy type.</div>
                                            </div>

                                            <!-- Coverage Type -->
                                            <div class="col-md-6 mb-3">
                                                <label for="coverage_type" class="form-label">Coverage Type <span class="text-danger">*</span></label>
                                                <select class="form-select" id="coverage_type" name="coverage_type" required>
                                                    <option value="">Select Coverage</option>
                                                    <option value="HEALTH">Health</option>
                                                    <option value="MOTOR">Motor</option>
                                                    <option value="LIFE">Life</option>
                                                    <option value="PROPERTY">Property</option>
                                                    <option value="TRAVEL">Travel</option>
                                                    <option value="MICRO">Micro</option>
                                                    <option value="BUNDLE">Bundle</option>
                                                </select>
                                                <div class="invalid-feedback">Please select coverage type.</div>
                                            </div>

                                            <!-- Sum Assured -->
                                            <div class="col-md-6 mb-3">
                                                <label for="sum_assured" class="form-label">Sum Assured (KSH) <span class="text-danger">*</span></label>
                                                <input type="number" class="form-control" id="sum_assured" name="sum_assured" 
                                                       step="0.01" min="0" required>
                                                <div class="invalid-feedback">Please enter sum assured.</div>
                                            </div>

                                            <!-- Premium Amount -->
                                            <div class="col-md-6 mb-3">
                                                <label for="premium_amount" class="form-label">Premium Amount (KSH) <span class="text-danger">*</span></label>
                                                <input type="number" class="form-control" id="premium_amount" name="premium_amount" 
                                                       step="0.01" min="0" required>
                                                <div class="invalid-feedback">Please enter premium amount.</div>
                                            </div>

                                            <!-- Premium Frequency -->
                                            <div class="col-md-6 mb-3">
                                                <label for="premium_frequency" class="form-label">Premium Frequency <span class="text-danger">*</span></label>
                                                <select class="form-select" id="premium_frequency" name="premium_frequency" required>
                                                    <option value="">Select Frequency</option>
                                                    <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 class="invalid-feedback">Please select premium frequency.</div>
                                            </div>

                                            <!-- Policy Term -->
                                            <div class="col-md-6 mb-3">
                                                <label for="policy_term_months" class="form-label">Policy Term (Months) <span class="text-danger">*</span></label>
                                                <input type="number" class="form-control" id="policy_term_months" name="policy_term_months" 
                                                       min="1" max="60" value="12" required>
                                                <div class="invalid-feedback">Please enter policy term.</div>
                                            </div>

                                            <!-- Inception Date -->
                                            <div class="col-md-6 mb-3">
                                                <label for="inception_date" class="form-label">Inception Date <span class="text-danger">*</span></label>
                                                <input type="date" class="form-control" id="inception_date" name="inception_date" 
                                                       value="<?php echo date('Y-m-d'); ?>" required>
                                                <div class="invalid-feedback">Please select inception date.</div>
                                            </div>

                                            <!-- Commission Rate -->
                                            <div class="col-md-6 mb-3">
                                                <label for="commission_rate" class="form-label">Commission Rate (%) <span class="text-danger">*</span></label>
                                                <input type="number" class="form-control" id="commission_rate" name="commission_rate" 
                                                       step="0.01" min="0" max="100" required>
                                                <div class="invalid-feedback">Please enter commission rate.</div>
                                            </div>

                                            <!-- Policy Fee -->
                                            <div class="col-md-6 mb-3">
                                                <label for="policy_fee" class="form-label">Policy Fee (KSH)</label>
                                                <input type="number" class="form-control" id="policy_fee" name="policy_fee" 
                                                       step="0.01" min="0" value="0">
                                            </div>

                                            <!-- Stamp Duty -->
                                            <div class="col-md-6 mb-3">
                                                <label for="stamp_duty" class="form-label">Stamp Duty (KSH)</label>
                                                <input type="number" class="form-control" id="stamp_duty" name="stamp_duty" 
                                                       step="0.01" min="0" value="0">
                                            </div>

                                            <!-- Special Conditions -->
                                            <div class="col-12 mb-3">
                                                <label for="special_conditions" class="form-label">Special Conditions</label>
                                                <textarea class="form-control" id="special_conditions" name="special_conditions" rows="3"></textarea>
                                            </div>

                                            <!-- Form Actions -->
                                            <div class="col-12">
                                                <div class="text-end">
                                                    <button type="button" class="btn btn-light me-2" onclick="window.history.back()">
                                                        <i class="ri-arrow-left-line me-1"></i> Cancel
                                                    </button>
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-save-line me-1"></i> Issue Policy
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('#customer_id, #product_id, #company_id, #agent_id').select2({
                theme: 'bootstrap-5'
            });

            // Initialize date picker
            flatpickr("#inception_date", {
                dateFormat: "Y-m-d",
                minDate: "today"
            });

            // Auto-populate coverage type based on product selection
            $('#product_id').change(function() {
                const selectedOption = $(this).find('option:selected');
                const coverageType = selectedOption.data('coverage');
                if (coverageType) {
                    $('#coverage_type').val(coverageType);
                }
            });

            // Form validation
            $('#policyForm').on('submit', function(e) {
                if (!this.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                $(this).addClass('was-validated');
            });

            // Calculate commission amount when premium or rate changes
            $('#premium_amount, #commission_rate').on('input', function() {
                const premium = parseFloat($('#premium_amount').val()) || 0;
                const rate = parseFloat($('#commission_rate').val()) || 0;
                const commission = (premium * rate) / 100;
                
                // Show calculated commission (you can add a display element for this)
                console.log('Calculated Commission: KSH ' + commission.toFixed(2));
            });
        });
    </script>
</body>
</html>