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

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

// Initialize QuotationManager
require_once 'QuotationManager.php';
$quotationManager = new QuotationManager($conn, $_SESSION['user_id'], $_SESSION['role_id']);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Gather quotation data
    $data = [
        'corp_id' => $_POST['corp_id'],
        'quotation_type' => $_POST['quotation_type'],
        'discount_percent' => !empty($_POST['discount_percent']) ? $_POST['discount_percent'] : 0,
        'discount_reason' => $_POST['discount_reason'] ?? null,
        'validity_days' => $_POST['validity_days'],
        'conversion_likelihood' => $_POST['conversion_likelihood'],
        'expected_close_date' => $_POST['expected_close_date'],
        'notes' => $_POST['notes'],
        'members' => []
    ];

    // Process member data
    $member_count = $_POST['member_count'];
    for ($i = 0; $i < $member_count; $i++) {
        if (isset($_POST["member_relation_$i"])) {
            $member = [
                'relation' => $_POST["member_relation_$i"],
                'age' => $_POST["member_age_$i"],
                'benefits' => []
            ];

            // Process benefits
            $benefit_count = $_POST["benefit_count_$i"];
            for ($j = 0; $j < $benefit_count; $j++) {
                if (isset($_POST["benefit_code_{$i}_{$j}"])) {
                    $benefit = [
                        'benefit_code' => $_POST["benefit_code_{$i}_{$j}"],
                        'limit_amount' => $_POST["benefit_limit_{$i}_{$j}"]
                    ];
                    
                    $member['benefits'][] = $benefit;
                }
            }
            
            $data['members'][] = $member;
        }
    }

    // Generate quotation
    $result = $quotationManager->generateQuotation($data);
    
    if ($result['success']) {
        // Set success message and redirect to view page
        $_SESSION['success_message'] = "Quotation {$result['quotation_no']} created successfully.";
        header("Location: view_quotation.php?id={$result['quotation_no']}");
        exit();
    } else {
        // Set error message
        $error_message = $result['error'];
    }
}

// Get corporates for dropdown
$sql = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$corporates = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);

// Get benefits for dropdown
$sql = "SELECT code, benefit FROM benefit ORDER BY code";
$benefits = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);

// Get the discount approval threshold from settings
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'discount_approval_threshold'";
$result = $conn->query($sql);
$discount_threshold = $result->fetch_assoc()['setting_value'] ?? 10; // Default 10%

// If there's a lead_id in the query parameters, populate data from the lead
$lead = null;
if (!empty($_GET['lead_id'])) {
    $lead_id = $_GET['lead_id'];
    $sql = "SELECT l.*, c.corp_id FROM sales_leads l LEFT JOIN corporate c ON l.client_name = c.corporate WHERE l.lead_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $lead_id);
    $stmt->execute();
    $lead = $stmt->get_result()->fetch_assoc();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Quotation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Sales', 'title' => 'Create Quotation')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">New Quotation</h4>
                                </div>
                                
                                <div class="card-body">
                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger" role="alert">
                                            <?php echo $error_message; ?>
                                        </div>
                                    <?php endif; ?>

                                    <form id="quotationForm" method="post" action="" class="needs-validation" novalidate>
                                        <!-- Corporate Info Section -->
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="card border">
                                                    <div class="card-header bg-soft-primary">
                                                        <h5 class="card-title mb-0">Corporate Information</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row g-3">
                                                            <div class="col-md-6">
                                                                <label class="form-label">Corporate</label>
                                                                <select class="form-select" id="corporateSelect" name="corp_id" required>
                                                                    <option value="">Select Corporate</option>
                                                                    <?php foreach ($corporates as $corporate): ?>
                                                                        <option value="<?php echo $corporate['corp_id']; ?>" <?php echo ($lead && $lead['corp_id'] == $corporate['corp_id']) ? 'selected' : ''; ?>>
                                                                            <?php echo htmlspecialchars($corporate['corporate']); ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                                <div class="invalid-feedback">Please select a corporate</div>
                                                            </div>
                                                            
                                                            <div class="col-md-6">
                                                                <label class="form-label">Quotation Type</label>
                                                                <select class="form-select" name="quotation_type" required>
                                                                    <option value="NEW">New Business</option>
                                                                    <option value="ADDITIONAL">Additional Coverage</option>
                                                                </select>
                                                                <div class="invalid-feedback">Please select quotation type</div>
                                                            </div>
                                                            
                                                            <div class="col-md-4">
                                                                <label class="form-label">Validity (Days)</label>
                                                                <input type="number" class="form-control" name="validity_days" value="30" min="1" max="90" required>
                                                                <div class="invalid-feedback">Please specify validity days (1-90)</div>
                                                            </div>
                                                            
                                                            <div class="col-md-4">
                                                                <label class="form-label">Conversion Likelihood</label>
                                                                <select class="form-select" name="conversion_likelihood" required>
                                                                    <option value="HIGH">High</option>
                                                                    <option value="MEDIUM" selected>Medium</option>
                                                                    <option value="LOW">Low</option>
                                                                </select>
                                                                <div class="invalid-feedback">Please select conversion likelihood</div>
                                                            </div>
                                                            
                                                            <div class="col-md-4">
                                                                <label class="form-label">Expected Close Date</label>
                                                                <input type="date" class="form-control" name="expected_close_date" 
                                                                    value="<?php echo $lead && $lead['expected_close_date'] ? $lead['expected_close_date'] : date('Y-m-d', strtotime('+30 days')); ?>" required>
                                                                <div class="invalid-feedback">Please specify expected close date</div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Members Section -->
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="card border">
                                                    <div class="card-header bg-soft-primary d-flex justify-content-between align-items-center">
                                                        <h5 class="card-title mb-0">Member Information</h5>
                                                        <button type="button" class="btn btn-sm btn-primary" id="addMemberBtn">
                                                            <i class="ri-user-add-line align-bottom me-1"></i> Add Member
                                                        </button>
                                                    </div>
                                                    <div class="card-body">
                                                        <div id="membersContainer">
                                                            <!-- Member forms will be added here dynamically -->
                                                        </div>
                                                        <input type="hidden" name="member_count" id="memberCount" value="0">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Discount Section -->
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="card border">
                                                    <div class="card-header bg-soft-primary">
                                                        <h5 class="card-title mb-0">Discount Information</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row g-3">
                                                            <div class="col-md-4">
                                                                <label class="form-label">Discount (%)</label>
                                                                <input type="number" class="form-control" name="discount_percent" id="discountPercent" min="0" max="30" step="0.5" value="0">
                                                                <small class="text-muted">Discounts over <?php echo $discount_threshold; ?>% require approval</small>
                                                            </div>
                                                            
                                                            <div class="col-md-8">
                                                                <label class="form-label">Discount Reason</label>
                                                                <textarea class="form-control" name="discount_reason" id="discountReason" rows="2" placeholder="Required if applying discount"></textarea>
                                                                <div class="invalid-feedback">Please provide a reason for the discount</div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Notes Section -->
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="card border">
                                                    <div class="card-header bg-soft-primary">
                                                        <h5 class="card-title mb-0">Additional Notes</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <textarea class="form-control" name="notes" rows="3" placeholder="Any additional details or notes about this quotation"><?php echo $lead ? $lead['notes'] : ''; ?></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Summary Section -->
                                        <div class="row mb-4">
                                            <div class="col-lg-12">
                                                <div class="card border">
                                                    <div class="card-header bg-soft-primary">
                                                        <h5 class="card-title mb-0">Quotation Summary</h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <table class="table table-sm table-borderless mb-0">
                                                                    <tr>
                                                                        <th width="180">Total Members:</th>
                                                                        <td id="summaryTotalMembers">0</td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Total Premium:</th>
                                                                        <td id="summaryTotalPremium">KES 0.00</td>
                                                                    </tr>
                                                                </table>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <table class="table table-sm table-borderless mb-0">
                                                                    <tr>
                                                                        <th width="180">Discount Amount:</th>
                                                                        <td id="summaryDiscountAmount">KES 0.00</td>
                                                                    </tr>
                                                                    <tr>
                                                                        <th>Final Premium:</th>
                                                                        <td id="summaryFinalPremium">KES 0.00</td>
                                                                    </tr>
                                                                </table>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Form Actions -->
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="hstack gap-2 justify-content-end">
                                                    <a href="quotation_management.php" class="btn btn-light">Cancel</a>
                                                    <button type="submit" class="btn btn-primary" id="submitBtn">
                                                        Generate Quotation
                                                    </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="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('quotationForm');
            const membersContainer = document.getElementById('membersContainer');
            const addMemberBtn = document.getElementById('addMemberBtn');
            const memberCountInput = document.getElementById('memberCount');
            const discountPercentInput = document.getElementById('discountPercent');
            const discountReasonInput = document.getElementById('discountReason');
            
            let memberCount = 0;
            let totalPremium = 0;
            
            // Add member button click handler
            addMemberBtn.addEventListener('click', function() {
                addMemberForm();
            });
            
            // Form submission handler
            form.addEventListener('submit', function(e) {
                if (!validateForm()) {
                    e.preventDefault();
                    e.stopPropagation();
                    form.classList.add('was-validated');
                }
            });
            
            // Discount input handler
            discountPercentInput.addEventListener('input', function() {
                updateSummary();
                validateDiscount();
            });
            
            // Add first member form automatically
            addMemberForm();
            
            // Function to add new member form
            function addMemberForm() {
                const memberIndex = memberCount;
                
                const memberCard = document.createElement('div');
                memberCard.className = 'card border member-card mb-3';
                memberCard.dataset.memberIndex = memberIndex;
                
                memberCard.innerHTML = `
                    <div class="card-header bg-soft-light d-flex justify-content-between align-items-center">
                        <h6 class="card-title mb-0">Member #${memberIndex + 1}</h6>
                        ${memberIndex > 0 ? `<button type="button" class="btn btn-sm btn-danger remove-member" data-index="${memberIndex}">
                            <i class="ri-delete-bin-line align-bottom"></i>
                        </button>` : ''}
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Relationship</label>
                                <select class="form-select" name="member_relation_${memberIndex}" required>
                                    <option value="">Select Relationship</option>
                                    <option value="principal" ${memberIndex === 0 ? 'selected' : ''}>Principal</option>
                                    <option value="spouse" ${memberIndex === 0 ? 'disabled' : ''}>Spouse</option>
                                    <option value="child" ${memberIndex === 0 ? 'disabled' : ''}>Child</option>
                                </select>
                                <div class="invalid-feedback">Please select relationship</div>
                            </div>
                            
                            <div class="col-md-4">
                                <label class="form-label">Age</label>
                                <input type="number" class="form-control" name="member_age_${memberIndex}" min="0" max="100" required>
                                <div class="invalid-feedback">Please enter valid age (0-100)</div>
                            </div>
                            
                            <div class="col-md-4">
                                <label class="form-label">&nbsp;</label>
                                <button type="button" class="btn btn-secondary w-100 add-benefit" data-member-index="${memberIndex}">
                                    <i class="ri-add-line align-bottom me-1"></i> Add Benefit
                                </button>
                            </div>
                        </div>
                        
                        <div class="benefits-container mt-3" data-member-index="${memberIndex}">
                            <!-- Benefits will be added here -->
                        </div>
                        <input type="hidden" name="benefit_count_${memberIndex}" id="benefitCount_${memberIndex}" value="0">
                    </div>
                `;
                
                membersContainer.appendChild(memberCard);
                
                // Add event listener for add benefit button
                const addBenefitBtn = memberCard.querySelector('.add-benefit');
                addBenefitBtn.addEventListener('click', function() {
                    const memberIndex = this.dataset.memberIndex;
                    addBenefitForm(memberIndex);
                });
                
                // Add event listener for remove member button
                const removeBtn = memberCard.querySelector('.remove-member');
                if (removeBtn) {
                    removeBtn.addEventListener('click', function() {
                        const memberIndex = this.dataset.index;
                        removeMember(memberIndex);
                    });
                }
                
                // Add initial benefit for this member
                addBenefitForm(memberIndex);
                
                // Update member count
                memberCount++;
                memberCountInput.value = memberCount;
                
                // Update summary
                updateSummary();
            }
            
            // Function to add benefit form
            function addBenefitForm(memberIndex) {
                const benefitsContainer = document.querySelector(`.benefits-container[data-member-index="${memberIndex}"]`);
                const benefitCountInput = document.getElementById(`benefitCount_${memberIndex}`);
                const benefitIndex = parseInt(benefitCountInput.value);
                
                const benefitRow = document.createElement('div');
                benefitRow.className = 'row g-3 mb-2 benefit-row';
                benefitRow.dataset.benefitIndex = benefitIndex;
                
                benefitRow.innerHTML = `
                    <div class="col-md-4">
                        <label class="form-label">Benefit Type</label>
                        <select class="form-select benefit-select" name="benefit_code_${memberIndex}_${benefitIndex}" data-member-index="${memberIndex}" data-benefit-index="${benefitIndex}" required>
                            <option value="">Select Benefit</option>
                            <?php foreach ($benefits as $benefit): ?>
                                <option value="<?php echo $benefit['code']; ?>"><?php echo htmlspecialchars($benefit['benefit']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="invalid-feedback">Please select benefit type</div>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label">Limit Amount (KES)</label>
                        <input type="number" class="form-control benefit-limit" name="benefit_limit_${memberIndex}_${benefitIndex}" data-member-index="${memberIndex}" data-benefit-index="${benefitIndex}" min="1000" step="1000" required>
                        <div class="invalid-feedback">Please enter valid limit amount</div>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">Premium (KES)</label>
                        <input type="text" class="form-control benefit-premium" name="benefit_premium_${memberIndex}_${benefitIndex}" data-member-index="${memberIndex}" data-benefit-index="${benefitIndex}" readonly>
                    </div>
                    
                    <div class="col-md-1">
                        <label class="form-label d-block">&nbsp;</label>
                        ${benefitIndex > 0 ? `<button type="button" class="btn btn-sm btn-danger remove-benefit" data-member-index="${memberIndex}" data-benefit-index="${benefitIndex}">
                            <i class="ri-delete-bin-line align-bottom"></i>
                        </button>` : ''}
                    </div>
                `;
                
                benefitsContainer.appendChild(benefitRow);
                
                // Add event listeners for benefit inputs
                const benefitSelect = benefitRow.querySelector('.benefit-select');
                const benefitLimit = benefitRow.querySelector('.benefit-limit');
                
                benefitSelect.addEventListener('change', function() {
                    calculatePremium(this.dataset.memberIndex, this.dataset.benefitIndex);
                });
                
                benefitLimit.addEventListener('input', function() {
                    calculatePremium(this.dataset.memberIndex, this.dataset.benefitIndex);
                });
                
                // Add event listener for remove benefit button
                const removeBtn = benefitRow.querySelector('.remove-benefit');
                if (removeBtn) {
                    removeBtn.addEventListener('click', function() {
                        const memberIndex = this.dataset.memberIndex;
                        const benefitIndex = this.dataset.benefitIndex;
                        removeBenefit(memberIndex, benefitIndex);
                    });
                }
                
                // Update benefit count
                benefitCountInput.value = benefitIndex + 1;
            }
            
            // Function to remove member
            function removeMember(index) {
                const memberCard = document.querySelector(`.member-card[data-member-index="${index}"]`);
                if (memberCard) {
                    memberCard.remove();
                    updateSummary();
                }
            }
            
            // Function to remove benefit
            function removeBenefit(memberIndex, benefitIndex) {
                const benefitRow = document.querySelector(`.benefit-row[data-benefit-index="${benefitIndex}"]`);
                if (benefitRow) {
                    benefitRow.remove();
                    updateSummary();
                }
            }
            
            // Function to calculate premium based on benefit type and limit
            function calculatePremium(memberIndex, benefitIndex) {
                const benefitSelect = document.querySelector(`select[name="benefit_code_${memberIndex}_${benefitIndex}"]`);
                const benefitLimit = document.querySelector(`input[name="benefit_limit_${memberIndex}_${benefitIndex}"]`);
                const benefitPremium = document.querySelector(`input[name="benefit_premium_${memberIndex}_${benefitIndex}"]`);
                
                if (benefitSelect && benefitLimit && benefitPremium) {
                    const benefitCode = benefitSelect.value;
                    const limit = parseFloat(benefitLimit.value);
                    
                    if (benefitCode && !isNaN(limit)) {
                        // Calculate premium based on benefit type and limit
                        // This is a simplified calculation - in real world this would call an API or use more complex logic
                        let rate = 0;
                        switch (parseInt(benefitCode)) {
                            case 1: // Inpatient
                                rate = 0.05; // 5% of limit
                                break;
                            case 2: // Outpatient
                                rate = 0.08; // 8% of limit
                                break;
                            case 3: // Maternity
                                rate = 0.12; // 12% of limit
                                break;
                            case 14: // Dental
                                rate = 0.15; // 15% of limit
                                break;
                            case 15: // Optical
                                rate = 0.10; // 10% of limit
                                break;
                            default:
                                rate = 0.07; // 7% of limit
                        }
                        
                        // Apply age factor - would normally come from the form
                        const ageInput = document.querySelector(`input[name="member_age_${memberIndex}"]`);
                        let ageFactor = 1;
                        
                        if (ageInput && ageInput.value) {
                            const age = parseInt(ageInput.value);
                            if (age < 18) {
                                ageFactor = 0.7; // 30% discount for children
                            } else if (age > 60) {
                                ageFactor = 1.5; // 50% loading for seniors
                            } else if (age > 50) {
                                ageFactor = 1.25; // 25% loading for older adults
                            }
                        }
                        
                        const premium = limit * rate * ageFactor;
                        benefitPremium.value = premium.toFixed(2);
                        
                        // Update summary
                        updateSummary();
                    }
                }
            }
            
            // Function to update summary section
            function updateSummary() {
                const summaryTotalMembers = document.getElementById('summaryTotalMembers');
                const summaryTotalPremium = document.getElementById('summaryTotalPremium');
                const summaryDiscountAmount = document.getElementById('summaryDiscountAmount');
                const summaryFinalPremium = document.getElementById('summaryFinalPremium');
                
                // Count members
                const memberCards = document.querySelectorAll('.member-card');
                const visibleMembers = Array.from(memberCards).filter(card => card.style.display !== 'none');
                summaryTotalMembers.textContent = visibleMembers.length;
                
                // Calculate total premium
                totalPremium = 0;
                const premiumInputs = document.querySelectorAll('.benefit-premium');
                premiumInputs.forEach(input => {
                    const premium = parseFloat(input.value);
                    if (!isNaN(premium)) {
                        totalPremium += premium;
                    }
                });
                
                summaryTotalPremium.textContent = `KES ${totalPremium.toFixed(2)}`;
                
                // Calculate discount
                const discountPercent = parseFloat(discountPercentInput.value) || 0;
                const discountAmount = (totalPremium * discountPercent) / 100;
                summaryDiscountAmount.textContent = `KES ${discountAmount.toFixed(2)}`;
                
                // Calculate final premium
                const finalPremium = totalPremium - discountAmount;
                summaryFinalPremium.textContent = `KES ${finalPremium.toFixed(2)}`;
            }
            
            // Function to validate discount
            function validateDiscount() {
                const discountPercent = parseFloat(discountPercentInput.value) || 0;
                const discountThreshold = <?php echo $discount_threshold; ?>;
                
                if (discountPercent > 0) {
                    // Ensure reason is filled if discount is applied
                    discountReasonInput.setAttribute('required', 'required');
                    
                    // Warn about approval if over threshold
                    if (discountPercent > discountThreshold) {
                        Swal.fire({
                            title: 'Approval Required',
                            text: `Discounts over ${discountThreshold}% require approval from a manager or administrator.`,
                            icon: 'warning',
                            confirmButtonText: 'Understand'
                        });
                    }
                } else {
                    // Remove required attribute if no discount
                    discountReasonInput.removeAttribute('required');
                }
            }
            
            // Function to validate form before submission
            function validateForm() {
                let isValid = true;
                
                // Check if at least one member exists
                if (memberCount === 0) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'At least one member is required.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return false;
                }
                
                // Check if discount reason is provided when discount is applied
                const discountPercent = parseFloat(discountPercentInput.value) || 0;
                if (discountPercent > 0 && !discountReasonInput.value.trim()) {
                    discountReasonInput.classList.add('is-invalid');
                    isValid = false;
                } else {
                    discountReasonInput.classList.remove('is-invalid');
                }
                
                return isValid;
            }
        });
    </script>
</body>
</html>