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

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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

$user_id = $_SESSION['user_id'];
$success_message = '';
$error_message = '';

// Check if company_id is provided in URL (from view insurer page)
$preselected_company_id = isset($_GET['company_id']) ? (int)$_GET['company_id'] : null;
$preselected_company = null;

// If company is preselected, get company details and validate
if ($preselected_company_id) {
    $company_sql = "SELECT company_id, company_name, company_code FROM insurance_companies WHERE company_id = ? AND is_active = 1";
    $company_stmt = $conn->prepare($company_sql);
    $company_stmt->bind_param("i", $preselected_company_id);
    $company_stmt->execute();
    $company_result = $company_stmt->get_result();
    
    if ($company_result->num_rows > 0) {
        $preselected_company = $company_result->fetch_assoc();
    } else {
        // Invalid company ID, redirect to standalone page
        header('Location: add_product.php');
        exit();
    }
    $company_stmt->close();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate required fields
        $required_fields = ['product_name', 'category_id', 'company_id', 'coverage_type', 'product_type'];
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                throw new Exception("Please fill in all required fields.");
            }
        }

        // If company was preselected, ensure it matches the form submission
        if ($preselected_company_id && $_POST['company_id'] != $preselected_company_id) {
            throw new Exception("Invalid company selection.");
        }

        // Generate product code if not provided
        $product_code = !empty($_POST['product_code']) ? $_POST['product_code'] : generateProductCode($_POST['category_id'], $_POST['company_id']);
        
        // Check if product code already exists
        $check_code_sql = "SELECT product_id FROM insurance_products WHERE product_code = ?";
        $check_stmt = $conn->prepare($check_code_sql);
        $check_stmt->bind_param("s", $product_code);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception("Product code already exists. Please use a different code.");
        }
        $check_stmt->close();

        // Prepare data for insertion
        $product_name = trim($_POST['product_name']);
        $category_id = (int)$_POST['category_id'];
        $company_id = (int)$_POST['company_id'];
        $product_type = $_POST['product_type'];
        $coverage_type = $_POST['coverage_type'];
        $description = trim($_POST['description']);
        $age_range_min = !empty($_POST['age_range_min']) ? (int)$_POST['age_range_min'] : 0;
        $age_range_max = !empty($_POST['age_range_max']) ? (int)$_POST['age_range_max'] : 100;
        $sum_assured_min = !empty($_POST['sum_assured_min']) ? (float)$_POST['sum_assured_min'] : 0;
        $sum_assured_max = !empty($_POST['sum_assured_max']) ? (float)$_POST['sum_assured_max'] : null;
        $premium_type = $_POST['premium_type'];
        $base_premium = !empty($_POST['base_premium']) ? (float)$_POST['base_premium'] : null;
        $policy_term_months = !empty($_POST['policy_term_months']) ? (int)$_POST['policy_term_months'] : 12;
        $waiting_period_days = !empty($_POST['waiting_period_days']) ? (int)$_POST['waiting_period_days'] : 0;
        $free_look_period_days = !empty($_POST['free_look_period_days']) ? (int)$_POST['free_look_period_days'] : 15;
        $commission_rate = !empty($_POST['commission_rate']) ? (float)$_POST['commission_rate'] : 0;
        $underwriting_required = isset($_POST['underwriting_required']) ? 1 : 0;
        $medical_required = isset($_POST['medical_required']) ? 1 : 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $launch_date = !empty($_POST['launch_date']) ? $_POST['launch_date'] : null;
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;

        // Process JSON fields
        $key_features = [];
        if (!empty($_POST['key_features'])) {
            $features_array = explode("\n", trim($_POST['key_features']));
            foreach ($features_array as $feature) {
                if (trim($feature)) {
                    $key_features[] = trim($feature);
                }
            }
        }

        $benefits = [];
        if (!empty($_POST['benefits'])) {
            $benefits_array = explode("\n", trim($_POST['benefits']));
            foreach ($benefits_array as $benefit) {
                if (trim($benefit)) {
                    $benefits[] = trim($benefit);
                }
            }
        }

        $exclusions = [];
        if (!empty($_POST['exclusions'])) {
            $exclusions_array = explode("\n", trim($_POST['exclusions']));
            foreach ($exclusions_array as $exclusion) {
                if (trim($exclusion)) {
                    $exclusions[] = trim($exclusion);
                }
            }
        }

        // Insert product
        $insert_sql = "INSERT INTO insurance_products (
            product_code, product_name, category_id, company_id, product_type, coverage_type,
            description, key_features, benefits, exclusions, age_range_min, age_range_max,
            sum_assured_min, sum_assured_max, premium_type, base_premium, policy_term_months,
            waiting_period_days, free_look_period_days, commission_rate, underwriting_required,
            medical_required, is_active, launch_date, end_date, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

        $stmt = $conn->prepare($insert_sql);
        
        $key_features_json = !empty($key_features) ? json_encode($key_features) : null;
        $benefits_json = !empty($benefits) ? json_encode($benefits) : null;
        $exclusions_json = !empty($exclusions) ? json_encode($exclusions) : null;

        $stmt->bind_param("ssiisssssiiddsdiiidiiisss", 
            $product_code, $product_name, $category_id, $company_id, $product_type, $coverage_type,
            $description, $key_features_json, $benefits_json, $exclusions_json, $age_range_min, $age_range_max,
            $sum_assured_min, $sum_assured_max, $premium_type, $base_premium, $policy_term_months,
            $waiting_period_days, $free_look_period_days, $commission_rate, $underwriting_required,
            $medical_required, $is_active, $launch_date, $end_date
        );

        if ($stmt->execute()) {
            $product_id = $conn->insert_id;
            
            $success_message = "Product '{$product_name}' has been successfully created with code: {$product_code}";
            
            // Determine redirect URL based on source
            if ($preselected_company_id) {
                // Redirect back to company view page
                header("Location: view_insurer.php?id={$preselected_company_id}&success=product_created&product_name=" . urlencode($product_name));
            } else {
                // Redirect to product view page
                header("Location: view_product.php?id={$product_id}&success=created");
            }
            exit();
        } else {
            throw new Exception("Failed to create product. Please try again.");
        }

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Get categories for dropdown
$categories_sql = "SELECT category_id, category_name, category_code FROM product_categories WHERE is_active = 1 ORDER BY category_name";
$categories_result = $conn->query($categories_sql);

// Get companies for dropdown (all companies if not preselected)
if (!$preselected_company_id) {
    $companies_sql = "SELECT company_id, company_name, company_code FROM insurance_companies WHERE is_active = 1 ORDER BY company_name";
    $companies_result = $conn->query($companies_sql);
}

// Function to generate product code
function generateProductCode($category_id, $company_id) {
    global $conn;
    
    // Get category code
    $cat_sql = "SELECT category_code FROM product_categories WHERE category_id = ?";
    $cat_stmt = $conn->prepare($cat_sql);
    $cat_stmt->bind_param("i", $category_id);
    $cat_stmt->execute();
    $cat_result = $cat_stmt->get_result()->fetch_assoc();
    $cat_code = $cat_result['category_code'] ?? 'GEN';
    $cat_stmt->close();
    
    // Get company code
    $comp_sql = "SELECT company_code FROM insurance_companies WHERE company_id = ?";
    $comp_stmt = $conn->prepare($comp_sql);
    $comp_stmt->bind_param("i", $company_id);
    $comp_stmt->execute();
    $comp_result = $comp_stmt->get_result()->fetch_assoc();
    $comp_code = $comp_result['company_code'] ?? 'UNK';
    $comp_stmt->close();
    
    // Generate sequential number
    $count_sql = "SELECT COUNT(*) + 1 as next_number FROM insurance_products WHERE category_id = ? AND company_id = ?";
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param("ii", $category_id, $company_id);
    $count_stmt->execute();
    $count_result = $count_stmt->get_result()->fetch_assoc();
    $next_number = str_pad($count_result['next_number'], 3, '0', STR_PAD_LEFT);
    $count_stmt->close();
    
    return $cat_code . '-' . $comp_code . '-' . $next_number;
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Insurance Product - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <!-- Flatpickr CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .form-floating > .form-control {
            padding-top: 1.625rem;
            padding-bottom: 0.625rem;
        }
        
        .form-floating > label {
            padding: 1rem 0.75rem;
        }
        
        .section-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 15px;
            margin-bottom: 2rem;
        }
        
        .section-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 15px 15px 0 0;
            margin: -1px -1px 0 -1px;
        }
        
        .required-field::after {
            content: " *";
            color: #e74c3c;
            font-weight: bold;
        }
        
        .feature-input {
            min-height: 120px;
            resize: vertical;
        }
        
        .btn-generate {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
            color: white;
        }
        
        .btn-generate:hover {
            background: linear-gradient(135deg, #218838 0%, #1abc9c 100%);
            color: white;
        }
        
        .company-info-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 2px solid #667eea;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .company-badge {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
        }
    </style>
</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">
                                    Add Insurance Product
                                    <?php if ($preselected_company): ?>
                                        <small class="text-muted">for <?php echo htmlspecialchars($preselected_company['company_name']); ?></small>
                                    <?php endif; ?>
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <?php if ($preselected_company_id): ?>
                                            <li class="breadcrumb-item"><a href="list_insurers.php">Insurers</a></li>
                                            <li class="breadcrumb-item"><a href="view_insurer.php?id=<?php echo $preselected_company_id; ?>"><?php echo htmlspecialchars($preselected_company['company_name']); ?></a></li>
                                        <?php else: ?>
                                            <li class="breadcrumb-item"><a href="list_products.php">Products</a></li>
                                        <?php endif; ?>
                                        <li class="breadcrumb-item active">Add Product</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Company Info Card (when preselected) -->
                    <?php if ($preselected_company): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="company-info-card">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center">
                                        <i class="ri-building-line fs-3 text-primary me-3"></i>
                                        <div>
                                            <h6 class="mb-1">Creating product for:</h6>
                                            <div class="company-badge">
                                                <?php echo htmlspecialchars($preselected_company['company_name']); ?>
                                                <small class="ms-2 opacity-75">(<?php echo htmlspecialchars($preselected_company['company_code']); ?>)</small>
                                            </div>
                                        </div>
                                    </div>
                                    <a href="add_product.php" class="btn btn-outline-secondary btn-sm">
                                        <i class="ri-edit-line me-1"></i>
                                        Change Company
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

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

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

                    <form method="POST" id="addProductForm" novalidate>
                        <!-- Hidden field for preselected company -->
                        <?php if ($preselected_company_id): ?>
                            <input type="hidden" name="company_id" value="<?php echo $preselected_company_id; ?>">
                        <?php endif; ?>
                        
                        <div class="row">
                            <!-- Basic Information -->
                            <div class="col-xl-8">
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-information-line me-2"></i>
                                            Basic Product Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="product_name" name="product_name" 
                                                           placeholder="Product Name" required 
                                                           value="<?php echo htmlspecialchars($_POST['product_name'] ?? ''); ?>">
                                                    <label for="product_name" class="required-field">Product Name</label>
                                                    <div class="invalid-feedback">Please provide a product name.</div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="product_code" name="product_code" 
                                                           placeholder="Product Code" 
                                                           value="<?php echo htmlspecialchars($_POST['product_code'] ?? ''); ?>">
                                                    <label for="product_code">Product Code</label>
                                                    <div class="form-text">Leave empty to auto-generate</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label required-field">Category</label>
                                                <select class="form-select" name="category_id" id="category_id" required>
                                                    <option value="">Select Category</option>
                                                    <?php while($cat = $categories_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $cat['category_id']; ?>" 
                                                                <?php echo (isset($_POST['category_id']) && $_POST['category_id'] == $cat['category_id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($cat['category_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                                <div class="invalid-feedback">Please select a category.</div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label required-field">Insurance Company</label>
                                                <?php if ($preselected_company): ?>
                                                    <!-- Show preselected company as read-only -->
                                                    <div class="form-control d-flex align-items-center" style="background-color: #f8f9fa;">
                                                        <i class="ri-building-line text-primary me-2"></i>
                                                        <span class="fw-medium"><?php echo htmlspecialchars($preselected_company['company_name']); ?></span>
                                                        <span class="text-muted ms-2">(<?php echo htmlspecialchars($preselected_company['company_code']); ?>)</span>
                                                    </div>
                                                    <div class="form-text text-success">
                                                        <i class="ri-lock-line me-1"></i>Company pre-selected from insurer page
                                                    </div>
                                                <?php else: ?>
                                                    <!-- Show dropdown for company selection -->
                                                    <select class="form-select" name="company_id" id="company_id" required>
                                                        <option value="">Select Company</option>
                                                        <?php while($comp = $companies_result->fetch_assoc()): ?>
                                                            <option value="<?php echo $comp['company_id']; ?>" 
                                                                    <?php echo (isset($_POST['company_id']) && $_POST['company_id'] == $comp['company_id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($comp['company_name']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                    <div class="invalid-feedback">Please select an insurance company.</div>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label required-field">Coverage Type</label>
                                                <select class="form-select" name="coverage_type" required>
                                                    <option value="">Select Coverage Type</option>
                                                    <option value="HEALTH" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'HEALTH') ? 'selected' : ''; ?>>Health Insurance</option>
                                                    <option value="MOTOR" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'MOTOR') ? 'selected' : ''; ?>>Motor Insurance</option>
                                                    <option value="LIFE" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'LIFE') ? 'selected' : ''; ?>>Life Insurance</option>
                                                    <option value="PROPERTY" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'PROPERTY') ? 'selected' : ''; ?>>Property Insurance</option>
                                                    <option value="TRAVEL" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'TRAVEL') ? 'selected' : ''; ?>>Travel Insurance</option>
                                                    <option value="MICRO" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'MICRO') ? 'selected' : ''; ?>>Micro Insurance</option>
                                                    <option value="BUNDLE" <?php echo (isset($_POST['coverage_type']) && $_POST['coverage_type'] == 'BUNDLE') ? 'selected' : ''; ?>>Bundle Package</option>
                                                </select>
                                                <div class="invalid-feedback">Please select a coverage type.</div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label required-field">Product Type</label>
                                                <select class="form-select" name="product_type" required>
                                                    <option value="">Select Product Type</option>
                                                    <option value="INDIVIDUAL" <?php echo (isset($_POST['product_type']) && $_POST['product_type'] == 'INDIVIDUAL') ? 'selected' : ''; ?>>Individual</option>
                                                    <option value="FAMILY" <?php echo (isset($_POST['product_type']) && $_POST['product_type'] == 'FAMILY') ? 'selected' : ''; ?>>Family</option>
                                                    <option value="GROUP" <?php echo (isset($_POST['product_type']) && $_POST['product_type'] == 'GROUP') ? 'selected' : ''; ?>>Group</option>
                                                    <option value="CORPORATE" <?php echo (isset($_POST['product_type']) && $_POST['product_type'] == 'CORPORATE') ? 'selected' : ''; ?>>Corporate</option>
                                                </select>
                                                <div class="invalid-feedback">Please select a product type.</div>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-floating">
                                                <textarea class="form-control" id="description" name="description" 
                                                          style="height: 100px" placeholder="Product Description"><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                                                <label for="description">Product Description</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Coverage & Premium Details -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-money-dollar-circle-line me-2"></i>
                                            Coverage & Premium Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="number" class="form-control" id="age_range_min" name="age_range_min" 
                                                           min="0" max="100" placeholder="Minimum Age" 
                                                           value="<?php echo htmlspecialchars($_POST['age_range_min'] ?? '0'); ?>">
                                                    <label for="age_range_min">Minimum Age</label>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="number" class="form-control" id="age_range_max" name="age_range_max" 
                                                           min="0" max="150" placeholder="Maximum Age" 
                                                           value="<?php echo htmlspecialchars($_POST['age_range_max'] ?? '100'); ?>">
                                                    <label for="age_range_max">Maximum Age</label>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="number" class="form-control" id="sum_assured_min" name="sum_assured_min" 
                                                           min="0" step="0.01" placeholder="Minimum Sum Assured" 
                                                           value="<?php echo htmlspecialchars($_POST['sum_assured_min'] ?? ''); ?>">
                                                    <label for="sum_assured_min">Minimum Sum Assured (KSH)</label>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="number" class="form-control" id="sum_assured_max" name="sum_assured_max" 
                                                           min="0" step="0.01" placeholder="Maximum Sum Assured" 
                                                           value="<?php echo htmlspecialchars($_POST['sum_assured_max'] ?? ''); ?>">
                                                    <label for="sum_assured_max">Maximum Sum Assured (KSH)</label>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Premium Type</label>
                                                <select class="form-select" name="premium_type">
                                                    <option value="CALCULATED" <?php echo (isset($_POST['premium_type']) && $_POST['premium_type'] == 'CALCULATED') ? 'selected' : ''; ?>>Calculated</option>
                                                    <option value="FIXED" <?php echo (isset($_POST['premium_type']) && $_POST['premium_type'] == 'FIXED') ? 'selected' : ''; ?>>Fixed</option>
                                                    <option value="TIERED" <?php echo (isset($_POST['premium_type']) && $_POST['premium_type'] == 'TIERED') ? 'selected' : ''; ?>>Tiered</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <div class="form-floating">
                                                    <input type="number" class="form-control" id="base_premium" name="base_premium" 
                                                           min="0" step="0.01" placeholder="Base Premium" 
                                                           value="<?php echo htmlspecialchars($_POST['base_premium'] ?? ''); ?>">
                                                    <label for="base_premium">Base Premium (KSH)</label>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <div class="form-floating">
                                                    <input type="number" class="form-control" id="commission_rate" name="commission_rate" 
                                                           min="0" max="100" step="0.01" placeholder="Commission Rate" 
                                                           value="<?php echo htmlspecialchars($_POST['commission_rate'] ?? ''); ?>">
                                                    <label for="commission_rate">Commission Rate (%)</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Product Features -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-star-line me-2"></i>
                                            Product Features & Benefits
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Key Features</label>
                                                <textarea class="form-control feature-input" name="key_features" 
                                                          placeholder="Enter each feature on a new line"><?php echo htmlspecialchars($_POST['key_features'] ?? ''); ?></textarea>
                                                <div class="form-text">One feature per line</div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Benefits</label>
                                                <textarea class="form-control feature-input" name="benefits" 
                                                          placeholder="Enter each benefit on a new line"><?php echo htmlspecialchars($_POST['benefits'] ?? ''); ?></textarea>
                                                <div class="form-text">One benefit per line</div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Exclusions</label>
                                                <textarea class="form-control feature-input" name="exclusions" 
                                                          placeholder="Enter each exclusion on a new line"><?php echo htmlspecialchars($_POST['exclusions'] ?? ''); ?></textarea>
                                                <div class="form-text">One exclusion per line</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Configuration Panel -->
                            <div class="col-xl-4">
                                <!-- Policy Configuration -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-settings-3-line me-2"></i>
                                            Policy Configuration
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <div class="form-floating">
                                                <input type="number" class="form-control" id="policy_term_months" name="policy_term_months" 
                                                       min="1" max="120" placeholder="Policy Term" 
                                                       value="<?php echo htmlspecialchars($_POST['policy_term_months'] ?? '12'); ?>">
                                                <label for="policy_term_months">Policy Term (Months)</label>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-floating">
                                                <input type="number" class="form-control" id="waiting_period_days" name="waiting_period_days" 
                                                       min="0" max="365" placeholder="Waiting Period" 
                                                       value="<?php echo htmlspecialchars($_POST['waiting_period_days'] ?? '0'); ?>">
                                                <label for="waiting_period_days">Waiting Period (Days)</label>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-floating">
                                                <input type="number" class="form-control" id="free_look_period_days" name="free_look_period_days" 
                                                       min="0" max="90" placeholder="Free Look Period" 
                                                       value="<?php echo htmlspecialchars($_POST['free_look_period_days'] ?? '15'); ?>">
                                                <label for="free_look_period_days">Free Look Period (Days)</label>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="underwriting_required" 
                                                       name="underwriting_required" 
                                                       <?php echo (isset($_POST['underwriting_required'])) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="underwriting_required">
                                                    Underwriting Required
                                                </label>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="medical_required" 
                                                       name="medical_required" 
                                                       <?php echo (isset($_POST['medical_required'])) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="medical_required">
                                                    Medical Examination Required
                                                </label>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="is_active" 
                                                       name="is_active" checked>
                                                <label class="form-check-label" for="is_active">
                                                    Active Product
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Launch Dates -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-calendar-line me-2"></i>
                                            Launch & Availability
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label">Launch Date</label>
                                            <input type="date" class="form-control" name="launch_date" 
                                                   value="<?php echo htmlspecialchars($_POST['launch_date'] ?? date('Y-m-d')); ?>">
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">End Date (Optional)</label>
                                            <input type="date" class="form-control" name="end_date" 
                                                   value="<?php echo htmlspecialchars($_POST['end_date'] ?? ''); ?>">
                                            <div class="form-text">Leave empty for no end date</div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Quick Actions -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-tools-line me-2"></i>
                                            Quick Actions
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if (!$preselected_company_id): ?>
                                        <button type="button" class="btn btn-generate w-100 mb-3" onclick="generateProductCode()">
                                            <i class="ri-magic-line me-2"></i>
                                            Generate Product Code
                                        </button>
                                        <?php else: ?>
                                        <button type="button" class="btn btn-generate w-100 mb-3" onclick="generateProductCodeWithCompany(<?php echo $preselected_company_id; ?>)">
                                            <i class="ri-magic-line me-2"></i>
                                            Generate Product Code
                                        </button>
                                        <?php endif; ?>

                                        <button type="button" class="btn btn-outline-info w-100 mb-3" onclick="previewProduct()">
                                            <i class="ri-eye-line me-2"></i>
                                            Preview Product
                                        </button>

                                        <hr>

                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-2"></i>
                                                Create Product
                                            </button>
                                            
                                            <?php if ($preselected_company_id): ?>
                                                <a href="view_insurer.php?id=<?php echo $preselected_company_id; ?>" class="btn btn-secondary">
                                                    <i class="ri-arrow-left-line me-2"></i>
                                                    Back to <?php echo htmlspecialchars($preselected_company['company_name']); ?>
                                                </a>
                                            <?php else: ?>
                                                <a href="list_products.php" class="btn btn-secondary">
                                                    <i class="ri-arrow-left-line me-2"></i>
                                                    Back to Products
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

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

    <!-- Product Preview Modal -->
    <div class="modal fade" id="productPreviewModal" tabindex="-1" aria-labelledby="productPreviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="productPreviewModalLabel">Product Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="productPreviewContent">
                    <!-- Preview content will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" form="addProductForm" class="btn btn-primary">Create Product</button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <!-- Flatpickr JS -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2 for dropdowns (excluding preselected company)
            $('.form-select:not([readonly])').select2({
                theme: 'bootstrap-5',
                width: '100%'
            });
            
            // Initialize date picker
            flatpickr('[type="date"]', {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Form validation
            $('#addProductForm').on('submit', function(e) {
                if (!this.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                this.classList.add('was-validated');
            });
            
            // Auto-generate product code when category changes (if company is preselected)
            <?php if ($preselected_company_id): ?>
            $('#category_id').on('change', function() {
                if ($(this).val() && !$('#product_code').val()) {
                    generateProductCodeWithCompany(<?php echo $preselected_company_id; ?>);
                }
            });
            <?php else: ?>
            // Auto-generate product code when category or company changes
            $('#category_id, #company_id').on('change', function() {
                if ($('#category_id').val() && $('#company_id').val() && !$('#product_code').val()) {
                    generateProductCode();
                }
            });
            <?php endif; ?>
            
            // Validate age ranges
            $('#age_range_min, #age_range_max').on('change', function() {
                const minAge = parseInt($('#age_range_min').val()) || 0;
                const maxAge = parseInt($('#age_range_max').val()) || 100;
                
                if (minAge > maxAge) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Age Range',
                        text: 'Minimum age cannot be greater than maximum age.',
                        confirmButtonText: 'OK'
                    });
                    $(this).focus();
                }
            });
            
            // Validate sum assured ranges
            $('#sum_assured_min, #sum_assured_max').on('change', function() {
                const minSum = parseFloat($('#sum_assured_min').val()) || 0;
                const maxSum = parseFloat($('#sum_assured_max').val()) || 0;
                
                if (maxSum > 0 && minSum > maxSum) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Sum Assured Range',
                        text: 'Minimum sum assured cannot be greater than maximum sum assured.',
                        confirmButtonText: 'OK'
                    });
                    $(this).focus();
                }
            });
        });
        
        // Generate product code (when no company is preselected)
        function generateProductCode() {
            const categoryId = $('#category_id').val();
            const companyId = $('#company_id').val();
            
            if (!categoryId || !companyId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Information',
                    text: 'Please select both category and company first.',
                    confirmButtonText: 'OK'
                });
                return;
            }
            
            generateCodeFromSelections(categoryId, companyId);
        }
        
        // Generate product code with preselected company
        function generateProductCodeWithCompany(companyId) {
            const categoryId = $('#category_id').val();
            
            if (!categoryId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Information',
                    text: 'Please select a category first.',
                    confirmButtonText: 'OK'
                });
                return;
            }
            
            generateCodeFromSelections(categoryId, companyId);
        }
        
        // Common function to generate code
        function generateCodeFromSelections(categoryId, companyId) {
            // Get category and company text
            const categoryText = $('#category_id option:selected').text() || 'GEN';
            <?php if ($preselected_company_id): ?>
            const companyText = '<?php echo $preselected_company['company_code']; ?>';
            <?php else: ?>
            const companyText = $('#company_id option:selected').text() || 'UNK';
            <?php endif; ?>
            
            // Simple code generation
            const catCode = categoryText.substring(0, 3).toUpperCase();
            const compCode = companyText.substring(0, 3).toUpperCase();
            const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
            
            const generatedCode = `${catCode}-${compCode}-${randomNum}`;
            $('#product_code').val(generatedCode);
            
            // Show success message
            Swal.fire({
                icon: 'success',
                title: 'Code Generated',
                text: `Product code: ${generatedCode}`,
                timer: 2000,
                showConfirmButton: false
            });
        }
        
        function previewProduct() {
            // Collect form data
            const formData = {
                product_name: $('#product_name').val(),
                product_code: $('#product_code').val(),
                category: $('#category_id option:selected').text(),
                <?php if ($preselected_company_id): ?>
                company: '<?php echo htmlspecialchars($preselected_company['company_name']); ?>',
                <?php else: ?>
                company: $('#company_id option:selected').text(),
                <?php endif; ?>
                coverage_type: $('[name="coverage_type"]').val(),
                product_type: $('[name="product_type"]').val(),
                description: $('#description').val(),
                age_range_min: $('#age_range_min').val(),
                age_range_max: $('#age_range_max').val(),
                sum_assured_min: $('#sum_assured_min').val(),
                sum_assured_max: $('#sum_assured_max').val(),
                base_premium: $('#base_premium').val(),
                commission_rate: $('#commission_rate').val(),
                policy_term_months: $('#policy_term_months').val(),
                waiting_period_days: $('#waiting_period_days').val(),
                free_look_period_days: $('#free_look_period_days').val(),
                underwriting_required: $('#underwriting_required').is(':checked'),
                medical_required: $('#medical_required').is(':checked'),
                is_active: $('#is_active').is(':checked'),
                key_features: $('[name="key_features"]').val().split('\n').filter(f => f.trim()),
                benefits: $('[name="benefits"]').val().split('\n').filter(b => b.trim()),
                exclusions: $('[name="exclusions"]').val().split('\n').filter(e => e.trim())
            };
            
            // Generate preview HTML
            let previewHtml = `
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary">Basic Information</h6>
                        <table class="table table-sm">
                            <tr><td><strong>Product Name:</strong></td><td>${formData.product_name || 'Not specified'}</td></tr>
                            <tr><td><strong>Product Code:</strong></td><td>${formData.product_code || 'Auto-generated'}</td></tr>
                            <tr><td><strong>Category:</strong></td><td>${formData.category || 'Not selected'}</td></tr>
                            <tr><td><strong>Company:</strong></td><td>${formData.company || 'Not selected'}</td></tr>
                            <tr><td><strong>Coverage Type:</strong></td><td>${formData.coverage_type || 'Not selected'}</td></tr>
                            <tr><td><strong>Product Type:</strong></td><td>${formData.product_type || 'Not selected'}</td></tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-primary">Coverage Details</h6>
                        <table class="table table-sm">
                            <tr><td><strong>Age Range:</strong></td><td>${formData.age_range_min || '0'} - ${formData.age_range_max || '100'} years</td></tr>
                            <tr><td><strong>Sum Assured:</strong></td><td>KSH ${formatNumber(formData.sum_assured_min)} - KSH ${formatNumber(formData.sum_assured_max)}</td></tr>
                            <tr><td><strong>Base Premium:</strong></td><td>KSH ${formatNumber(formData.base_premium)}</td></tr>
                            <tr><td><strong>Commission:</strong></td><td>${formData.commission_rate || '0'}%</td></tr>
                            <tr><td><strong>Policy Term:</strong></td><td>${formData.policy_term_months || '12'} months</td></tr>
                            <tr><td><strong>Waiting Period:</strong></td><td>${formData.waiting_period_days || '0'} days</td></tr>
                        </table>
                    </div>
                </div>
            `;
            
            if (formData.description) {
                previewHtml += `
                    <div class="mt-3">
                        <h6 class="text-primary">Description</h6>
                        <p class="text-muted">${formData.description}</p>
                    </div>
                `;
            }
            
            if (formData.key_features.length > 0) {
                previewHtml += `
                    <div class="mt-3">
                        <h6 class="text-primary">Key Features</h6>
                        <ul class="list-unstyled">
                            ${formData.key_features.map(f => `<li class="mb-1">✓ ${f}</li>`).join('')}
                        </ul>
                    </div>
                `;
            }
            
            if (formData.benefits.length > 0) {
                previewHtml += `
                    <div class="mt-3">
                        <h6 class="text-primary">Benefits</h6>
                        <ul class="list-unstyled">
                            ${formData.benefits.map(b => `<li class="mb-1">+ ${b}</li>`).join('')}
                        </ul>
                    </div>
                `;
            }
            
            if (formData.exclusions.length > 0) {
                previewHtml += `
                    <div class="mt-3">
                        <h6 class="text-primary">Exclusions</h6>
                        <ul class="list-unstyled">
                            ${formData.exclusions.map(e => `<li class="mb-1">⨯ ${e}</li>`).join('')}
                        </ul>
                    </div>
                `;
            }
            
            previewHtml += `
                <div class="mt-3">
                    <h6 class="text-primary">Configuration</h6>
                    <div class="row">
                        <div class="col-md-4">
                            <span class="badge ${formData.underwriting_required ? 'bg-warning' : 'bg-success'}">
                                ${formData.underwriting_required ? 'Underwriting Required' : 'No Underwriting'}
                            </span>
                        </div>
                        <div class="col-md-4">
                            <span class="badge ${formData.medical_required ? 'bg-warning' : 'bg-success'}">
                                ${formData.medical_required ? 'Medical Required' : 'No Medical'}
                            </span>
                        </div>
                        <div class="col-md-4">
                            <span class="badge ${formData.is_active ? 'bg-success' : 'bg-secondary'}">
                                ${formData.is_active ? 'Active' : 'Inactive'}
                            </span>
                        </div>
                    </div>
                </div>
            `;
            
            $('#productPreviewContent').html(previewHtml);
            $('#productPreviewModal').modal('show');
        }
        
        function formatNumber(num) {
            if (!num || num === '') return '0';
            return parseFloat(num).toLocaleString();
        }
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>