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

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

try {
    // Get input data
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['corp_id']) || !isset($data['member'])) {
        throw new Exception('Missing required data');
    }

    // Initialize calculator
    $calculator = new PremiumCalculator($conn, $data['corp_id']);

    // Validate member data
    $validation_errors = $calculator->validateMemberLimits($data['member']);
    if (!empty($validation_errors)) {
        throw new Exception(implode(", ", $validation_errors));
    }

    // Calculate premium
    $premium_details = $calculator->calculatePremium($data['member']);

    // Return detailed premium breakdown
    echo json_encode([
        'success' => true,
        'premium_details' => $premium_details,
        'total_premium' => $premium_details['total_premium'],
        'taxes' => $premium_details['taxes'],
        'grand_total' => $premium_details['grand_total']
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

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

// Fetch benefits
$sql_benefits = "SELECT code, benefit FROM benefit ORDER BY benefit";
$result_benefits = $conn->query($sql_benefits);
$benefits = $result_benefits->fetch_all(MYSQLI_ASSOC);

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Generate Quotation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .member-row {
            background-color: #f8f9fa;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 5px;
        }
        .premium-card {
            transition: all 0.3s ease;
        }
        .premium-card:hover {
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
        }
        .email-section {
            display: none;
        }
        .email-section.active {
            display: block;
        }
    </style>
</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' => 'Quotations', 'title' => 'Generate 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">Generate Corporate Quotation</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form id="quotationForm" method="POST" action="save_quotation.php">
                                        <!-- Corporate Selection -->
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label class="form-label">Select Corporate</label>
                                                <select class="form-select" name="corp_id" id="corporateSelect" required>
                                                    <option value="">Select Corporate</option>
                                                    <?php foreach ($corporates as $corporate): ?>
                                                        <option value="<?php echo $corporate['corp_id']; ?>" 
                                                                data-scheme="<?php echo $corporate['scheme']; ?>">
                                                            <?php echo htmlspecialchars($corporate['corporate']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-3">
                                                <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 Members</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-3">
                                                <label class="form-label">Valid Until</label>
                                                <input type="date" class="form-control" name="valid_until" 
                                                       value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                            </div>
                                        </div>

                                        <!-- Members Section -->
                                        <div class="card border mb-4">
                                            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                                                <h5 class="mb-0">Members</h5>
                                                <button type="button" class="btn btn-secondary btn-sm me-2" id="downloadTemplateBtn">
                                                    <i class="ri-download-line align-middle"></i> Download Template
                                                </button>
                                                <button type="button" class="btn btn-info btn-sm me-2" id="importCsvBtn">
                                                    <i class="ri-upload-line align-middle"></i> Import CSV
                                                </button>
                                                <button type="button" class="btn btn-primary btn-sm" id="addMemberBtn">
                                                    <i class="ri-add-line align-middle"></i> Add Member
                                                </button>
                                                <input type="file" id="csvFileInput" accept=".csv" style="display: none;">
                                            </div>
                                            
                                            <div class="card-body">
                                                <div id="membersContainer">
                                                    <!-- Members will be added here dynamically -->
                                                </div>
                                                
                                                <div class="row justify-content-end">
                                                    <div class="col-md-4">
                                                        <div class="bg-light p-3 rounded">
                                                            <div class="d-flex justify-content-between">
                                                                <strong>Total Premium:</strong>
                                                                <span id="totalPremium" class="h4 mb-0">0.00</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Email Details Section -->
                                        <div class="card border">
                                            <div class="card-header bg-light">
                                                <h5 class="mb-0">Email Details</h5>
                                            </div>
                                            
                                            <div class="card-body">
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label class="form-label">To</label>
                                                        <input type="email" class="form-control" name="email_to" required>
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <label class="form-label">CC</label>
                                                        <input type="text" class="form-control" name="email_cc" 
                                                               placeholder="Separate multiple emails with commas">
                                                    </div>
                                                </div>

                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label class="form-label">BCC</label>
                                                        <input type="text" class="form-control" name="email_bcc" 
                                                               placeholder="Separate multiple emails with commas">
                                                    </div>
                                                    
                                                    <div class="col-md-6">
                                                        <label class="form-label">Subject</label>
                                                        <input type="text" class="form-control" name="email_subject" 
                                                               value="Insurance Quotation" required>
                                                    </div>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">Email Content</label>
                                                    <textarea class="form-control" name="email_content" rows="5" required>Dear Valued Client,

Please find attached your insurance quotation. This quotation is valid until {VALID_DATE}.

Best regards,
Insurance Team</textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Form Buttons -->
                                        <div class="row mt-4">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-end gap-2">
                                                    <button type="button" class="btn btn-light" id="previewBtn">
                                                        Preview
                                                    </button>
                                                    <button type="submit" class="btn btn-primary">
                                                        Generate & Send
                                                    </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() {
    // Initialize state and elements
    let memberCount = 0;
    const membersContainer = document.getElementById('membersContainer');
    const addMemberBtn = document.getElementById('addMemberBtn');
    const corporateSelect = document.getElementById('corporateSelect');
    const quotationForm = document.getElementById('quotationForm');
    const downloadTemplateBtn = document.getElementById('downloadTemplateBtn');
    const importCsvBtn = document.getElementById('importCsvBtn');
    const csvFileInput = document.getElementById('csvFileInput');

    // Template Download Handler
    downloadTemplateBtn?.addEventListener('click', function() {
        window.location.href = 'download_template.php';
    });

    // Import CSV Button Handler
    importCsvBtn?.addEventListener('click', function() {
        csvFileInput.click();
    });

    // CSV File Selection Handler
    csvFileInput?.addEventListener('change', function(e) {
        handleFileImport(e);
    });

    // Add Member Button Handler
    addMemberBtn?.addEventListener('click', function() {
        addNewMemberRow();
    });

    // Corporate Selection Change Handler
    corporateSelect?.addEventListener('change', function() {
        handleCorporateChange();
    });

    // Form Submission Handler
    quotationForm?.addEventListener('submit', function(e) {
        handleFormSubmit(e);
    });

    // Preview Button Handler
    document.getElementById('previewBtn')?.addEventListener('click', function() {
        handlePreview();
    });

    // Global Change Event Handler for Dynamic Elements
    document.addEventListener('change', function(e) {
        handleDynamicChanges(e);
    });

    // Core Functions

    function addNewMemberRow(memberData = null) {
        // Check corporate selection
        if (!corporateSelect.value) {
            Swal.fire({
                icon: 'warning',
                title: 'Corporate Required',
                text: 'Please select a corporate first before adding members.'
            });
            return;
        }

        // Create member row
        const memberRow = document.createElement('div');
        memberRow.className = 'member-row';
        memberRow.innerHTML = generateMemberRowHtml(memberCount);

        // If memberData provided, populate the row
        if (memberData) {
            populateMemberRow(memberRow, memberData);
        }

        // Add to container and initialize
        membersContainer.appendChild(memberRow);
        initializeMemberRow(memberRow);
        memberCount++;
        calculateTotalPremium();
    }

    function generateMemberRowHtml(index) {
        return `
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">Relation</label>
                    <select class="form-select" name="members[${index}][relation]" required>
                        <option value="">Select Relation</option>
                        <option value="principal">Principal</option>
                        <option value="spouse">Spouse</option>
                        <option value="child">Child</option>
                        <option value="parent">Parent</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">Age</label>
                    <input type="number" class="form-control member-age" 
                           name="members[${index}][age]" min="0" max="120" required>
                </div>
                
                <div class="col-md-5">
                    <label class="form-label">Benefits</label>
                    <div class="benefits-container">
                        <?php foreach ($benefits as $benefit): ?>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input benefit-checkbox" 
                                   type="checkbox" 
                                   name="members[${index}][benefits][]" 
                                   value="<?php echo $benefit['code']; ?>">
                            <label class="form-check-label">
                                <?php echo htmlspecialchars($benefit['benefit']); ?>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">Premium</label>
                    <input type="text" class="form-control member-premium" readonly>
                    <div class="premium-breakdown mt-2"></div>
                    <button type="button" class="btn btn-danger btn-sm mt-2 remove-member">
                        <i class="ri-delete-bin-line"></i> Remove
                    </button>
                </div>
            </div>
        `;
    }

    function initializeMemberRow(row) {
        // Add event listeners for the row
        const removeBtn = row.querySelector('.remove-member');
        const ageInput = row.querySelector('.member-age');
        const relationSelect = row.querySelector('select[name*="[relation]"]');
        const benefitChecks = row.querySelectorAll('.benefit-checkbox');

        removeBtn?.addEventListener('click', function() {
            row.remove();
            calculateTotalPremium();
        });

        [ageInput, relationSelect].forEach(input => {
            input?.addEventListener('change', () => calculateMemberPremium(row));
        });

        benefitChecks.forEach(check => {
            check.addEventListener('change', () => calculateMemberPremium(row));
        });
    }

    function calculateMemberPremium(row) {
        // Check corporate selection
        if (!corporateSelect.value) {
            Swal.fire({
                icon: 'warning',
                title: 'Corporate Required',
                text: 'Please select a corporate first.'
            });
            return;
        }

        // Get values
        const age = parseInt(row.querySelector('.member-age').value);
        const relation = row.querySelector('select[name*="[relation]"]').value;
        const selectedBenefits = Array.from(row.querySelectorAll('.benefit-checkbox:checked'))
            .map(cb => parseInt(cb.value));
        const premiumInput = row.querySelector('.member-premium');
        const breakdownDiv = row.querySelector('.premium-breakdown');

        // Validate inputs
        if (!age || !relation || selectedBenefits.length === 0) {
            premiumInput.value = '';
            breakdownDiv.innerHTML = '';
            calculateTotalPremium();
            return;
        }

        // Show loading state
        premiumInput.value = 'Calculating...';
        breakdownDiv.innerHTML = '<div class="text-muted small">Loading...</div>';

        // Calculate premium
        fetch('calculate_premium.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                corp_id: corporateSelect.value,
                member: { relation, age, benefits: selectedBenefits }
            })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) throw new Error(data.error || 'Failed to calculate premium');
            updatePremiumDisplay(row, data);
            calculateTotalPremium();
        })
        .catch(error => {
            console.error('Error:', error);
            premiumInput.value = '';
            breakdownDiv.innerHTML = `<div class="small text-danger">Error: ${error.message}</div>`;
            calculateTotalPremium();
        });
    }

    function updatePremiumDisplay(row, data) {
        const premiumInput = row.querySelector('.member-premium');
        const breakdownDiv = row.querySelector('.premium-breakdown');
        
        // Update premium value
        premiumInput.value = data.grand_total.toFixed(2);

        // Build breakdown HTML
        let breakdownHtml = '<div class="small text-muted">';
        breakdownHtml += '<strong>Premium Breakdown:</strong><ul class="list-unstyled mb-2">';

        // Add benefit premiums
        Object.entries(data.premium_details.benefit_premiums).forEach(([benefit, details]) => {
            breakdownHtml += `<li>${details.benefit_name}: ${parseFloat(details.final_premium).toFixed(2)}</li>`;
        });

        // Add subtotal and taxes
        breakdownHtml += `
            <li><strong>Total Premium:</strong> ${data.premium_details.total_premium.toFixed(2)}</li>
            <li class="mt-2"><strong>Taxes & Levies:</strong></li>
            <li>PHCF: ${data.premium_details.taxes.phcf.toFixed(2)}</li>
            <li>Training Levy: ${data.premium_details.taxes.training_levy.toFixed(2)}</li>
            <li>Stamp Duty: ${data.premium_details.taxes.stamp_duty.toFixed(2)}</li>
            <li class="mt-2"><strong>Grand Total:</strong> ${data.grand_total.toFixed(2)}</li>
        `;
        breakdownHtml += '</ul></div>';

        breakdownDiv.innerHTML = breakdownHtml;
    }

    function calculateTotalPremium() {
        const premiums = document.querySelectorAll('.member-premium');
        const total = Array.from(premiums)
            .reduce((sum, input) => sum + (parseFloat(input.value) || 0), 0);
        document.getElementById('totalPremium').textContent = total.toFixed(2);
    }

    function handleFileImport(e) {
        if (!e.target.files.length) return;

        const file = e.target.files[0];
        if (file.type !== 'text/csv' && file.type !== 'application/vnd.ms-excel') {
            Swal.fire({
                icon: 'error',
                title: 'Invalid File',
                text: 'Please upload a CSV file'
            });
            return;
        }

        if (!corporateSelect.value) {
            Swal.fire({
                icon: 'warning',
                title: 'Corporate Required',
                text: 'Please select a corporate before importing members'
            });
            return;
        }

        importMembers(file);
    }

    function importMembers(file) {
    Swal.fire({
        title: 'Importing...',
        text: 'Please wait while we process your file',
        allowOutsideClick: false,
        didOpen: () => { Swal.showLoading(); }
    });

    const formData = new FormData();
    formData.append('csv_file', file);

    fetch('import_csv.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(async data => { // Make this async to handle premium calculations sequentially
        if (!data.success) throw new Error(data.error);
        
        // Process each member sequentially to avoid race conditions
        for (const member of data.members) {
            await addNewMemberRow(member);
        }
        
        Swal.fire({
            icon: 'success',
            title: 'Import Successful',
            text: data.message
        });

        // Recalculate total after all members are imported
        calculateTotalPremium();
    })
    .catch(error => {
        console.error('Import error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Import Failed',
            text: error.message
        });
    })
    .finally(() => {
        csvFileInput.value = ''; // Reset file input
    });
}

    function populateMemberRow(row, memberData) {
        // Map benefit names to codes
        const benefitMap = {
            'inpatient': 1,
            'outpatient': 2,
            'maternity': 3
        };
    
        // Set basic values
        const relationSelect = row.querySelector('select[name*="[relation]"]');
        const ageInput = row.querySelector('.member-age');
        
        if (relationSelect) relationSelect.value = memberData.relation;
        if (ageInput) ageInput.value = memberData.age;
    
        // Set benefits
        memberData.benefits.forEach(benefit => {
            const benefitCode = benefitMap[benefit];
            if (benefitCode) {
                const checkbox = row.querySelector(`input[value="${benefitCode}"]`);
                if (checkbox) checkbox.checked = true;
            }
        });
    
        // Explicitly calculate premium after populating data
        calculateMemberPremium(row);
    }
    
    // Make addNewMemberRow return a Promise to handle async premium calculation
    async function addNewMemberRow(memberData = null) {
        // Check corporate selection
        if (!corporateSelect.value) {
            Swal.fire({
                icon: 'warning',
                title: 'Corporate Required',
                text: 'Please select a corporate first before adding members.'
            });
            return;
        }
    
        // Create member row
        const memberRow = document.createElement('div');
        memberRow.className = 'member-row';
        memberRow.innerHTML = generateMemberRowHtml(memberCount);
    
        // If memberData provided, populate the row
        if (memberData) {
            populateMemberRow(memberRow, memberData);
        }
    
        // Add to container and initialize
        membersContainer.appendChild(memberRow);
        initializeMemberRow(memberRow);
        memberCount++;
    
        // Wait for premium calculation to complete
        if (memberData) {
            await new Promise(resolve => {
                setTimeout(resolve, 500); // Small delay to ensure UI updates
            });
        }
    
        calculateTotalPremium();
    }

    function handleCorporateChange() {
        if (this.value === '') {
            membersContainer.innerHTML = '';
            document.getElementById('totalPremium').textContent = '0.00';
            return;
        }

        // Reset existing member premiums
        document.querySelectorAll('.member-row').forEach(row => {
            const premiumInput = row.querySelector('.member-premium');
            const breakdownDiv = row.querySelector('.premium-breakdown');
            if (premiumInput) premiumInput.value = '';
            if (breakdownDiv) breakdownDiv.innerHTML = '';
            calculateMemberPremium(row);
        });
    }

    function validateForm() {
        if (!quotationForm.checkValidity()) {
            quotationForm.reportValidity();
            return false;
        }

        const members = document.querySelectorAll('.member-row');
        if (members.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Members Required',
                text: 'Please add at least one member'
            });
            return false;
        }

        // Validate premiums
        let validPremiums = true;
        members.forEach(member => {
            const premium = member.querySelector('.member-premium').value;
            if (!premium || premium === 'Calculating...' || premium === '0.00') {
                validPremiums = false;
            }
        });

        if (!validPremiums) {
            Swal.fire({
                icon: 'warning',
                title: 'Invalid Premiums',
                text: 'Please ensure all members have valid benefits and calculated premiums'
            });
            return false;
        }

        return true;
    }

    function handleFormSubmit(e) {
        e.preventDefault();
        if (!validateForm()) return;

        Swal.fire({
            title: 'Saving...',
            text: 'Please wait while we process your quotation',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        fetch('save_quotation.php', {
            method: 'POST',
            body: new FormData(quotationForm)
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) throw new Error(data.error || 'Failed to save quotation');

            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: data.message,
                confirmButtonText: 'View Quotation',
                showCancelButton: true,
                cancelButtonText: 'Convert to Policy'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'view_quotation.php?no=' + data.quotation_no;
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    window.location.href = 'convert_quotation.php?quotation_no=' + data.quotation_no;
                }
            });
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message || 'Failed to save quotation'
            });
        });
    }

    function handlePreview() {
        if (!validateForm()) return;

        const formData = new FormData(quotationForm);
        formData.append('preview', '1');
        
        fetch('preview_quotation.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to generate preview');
            }
            return response.blob();
        })
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            window.open(url, '_blank');
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Preview Failed',
                text: error.message
            });
        });
    }

    function handleDynamicChanges(e) {
        // Handle benefit checkbox changes
        if (e.target.matches('.benefit-checkbox')) {
            const row = e.target.closest('.member-row');
            if (row) calculateMemberPremium(row);
        }

        // Handle age input changes
        if (e.target.matches('.member-age')) {
            const row = e.target.closest('.member-row');
            if (row) calculateMemberPremium(row);
        }

        // Handle relation selection changes
        if (e.target.matches('select[name*="[relation]"]')) {
            const row = e.target.closest('.member-row');
            if (row) calculateMemberPremium(row);
        }
    }
});
</script>
</body>
</html>