<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Policy Search</title>
    <link rel="stylesheet" href="<?php echo e(asset('style.css')); ?>">
</head>

<body>
    <!-- Hero Section -->
    <header class="hero">
        <div class="hero-content">
            <h1>Trust Online Premium Payment</h1>
            <p>Your one-stop solution for secure and easy premium payments.</p>
        </div>
    </header>

    <!-- Policy Search Section -->
    <section class="policy-search">
        <img src="<?php echo e(asset('trust logo2-1.png')); ?>" alt="Trust Islami Life Insurance Ltd." class="logo">
        <div class="search-container">

            <h2>Search Your Policy</h2>
            <p>Enter your policy number to view details and make payments.</p>
            <?php if(session('success')): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert" style="display: block;">
                    <?php echo session('success'); ?>

                    
                </div>
            <?php endif; ?>

            <?php if(session('error')): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert" style="display: block;">
                    <?php echo e(session('error')); ?>

                    
                </div>
            <?php endif; ?>
            <div class="alert" id="alertMessage" style="display: none;">Please enter a valid policy number.</div>

            <div class="search-box">
                <input type="text" id="policyNumber" placeholder="Enter Policy Number">
                <button onclick="searchPolicy()">Search</button>
            </div>
        </div>
    </section>

    <!-- Policy Details Section -->
    <section class="policy-details" id="policyCard">
        <h2 id="policyName">Policy Details</h2>
        <div class="details-container">
            <div class="details-card">
                <h3>Plan Details</h3>
                <p><strong>Plan Term:</strong> <span id="planTerm">10 years</span></p>
                <p><strong>Pay Mode:</strong> <span id="payMode">Half-Yearly</span></p>
                <p><strong>Sum Assured:</strong> <span id="sumAssured">BDT 500,000</span></p>
                <p><strong>Installment Premium:</strong> <span id="installPremium">BDT 10,000</span></p>
            </div>
            <div class="details-card">
                <h3>Important Dates</h3>
                <p><strong>Commencement Date:</strong> <span id="commencementDate">2020-06-01</span></p>
                <p><strong>Due Date:</strong> <span id="dueDate">2025-06-01</span></p>
            </div>
            <div class="details-card">
                <h3>Due Details</h3>
                <p><strong>Due Installments:</strong> <span id="dueInstallments">5</span></p>
                <p><strong>Due Premium:</strong> <span id="duePremium">BDT 50,000</span></p>
                <div class="input-group">
                    <label for="dueInstallmentInput">Installments to Pay:</label>
                    <input type="number" id="dueInstallmentInput" min="0" placeholder="Number"
                        oninput="validateInstallments()">
                </div>
                <p><strong>Total Amount:</strong> <span id="duePremiumDisplay">BDT 0</span></p>
            </div>
        </div>
        <button class="btn-primary" id="sslczPayBtn" token="if you have any token validation"
            postdata="your javascript arrays or objects which requires in backend"
            order="If you already have the transaction generated for current order"
            endpoint="<?php echo e(url('/pay-via-ajax')); ?>" style="background: #0099a1; width:38%">Pay Now</button>
    </section>

    <!-- Payment Methods Section -->


    <!-- Footer -->
    <footer class="footer">
        <section class="payment-methods">
            <img src="<?php echo e(asset('payment.jpg')); ?>" alt="Payment Methods" class="payment-icons">
        </section>
        <p style="font-size: 99%;">&copy; 2024 Trust Islami Life Insurance Ltd. All Rights Reserved.</p>
    </footer>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
    </script>
    <script>
        let currentPolicy = null;

        function validateInstallments() {
            const maxInstallments = parseInt(document.getElementById("dueInstallments").innerText) || 0;
            const inputField = document.getElementById("dueInstallmentInput");
            const inputValue = parseInt(inputField.value) || 0;
            if (inputField.value < 0) {
                inputField.value = 1; // Clear the input if it's negative
                alert('Installments cannot be negative.');
            }
            if (inputValue > maxInstallments) {
                alert(`The number of installments cannot exceed ${maxInstallments}.`);
                inputField.value = maxInstallments; // Reset to the maximum allowed
            }

            // Recalculate premium if the value is valid
            calculateDuePremium();
        }

        async function searchPolicy() {
            const policyNumber = document.getElementById("policyNumber").value.trim();
            const alertMessage = document.getElementById("alertMessage");
            const policyCard = document.getElementById("policyCard");
            const searchButton = document.querySelector(".search-box button");

            if (!policyNumber) {
                alertMessage.innerText = "Please enter a valid policy number."; // Set error message
                alertMessage.style.display = "block"; // Show alert
                return;
            }

            alertMessage.style.display = "none"; // Hide alert if input is valid

            // Show loader on button
            searchButton.innerText = "Loading...";
            searchButton.disabled = true;

            try {
                const response = await fetch(`/get/policy_data/${policyNumber}`, {
                    method: "GET"
                });

                if (!response.ok) {
                    alertMessage.innerText =
                        "Policy not found or an error occurred while fetching data."; // Set error message
                    alertMessage.style.display = "block"; // Show alert
                    policyCard.style.display = "none"; // Hide policy details card
                    return;
                }

                const data = await response.json();
                currentPolicy = data[0];

                if (currentPolicy) {
                    document.getElementById("policyName").innerText = `${currentPolicy.POLICY_NAME || "N/A"}`;
                    document.getElementById("planTerm").innerText = currentPolicy.PLANTERM || "N/A";
                    document.getElementById("payMode").innerText = currentPolicy.PAYMODE_DESC || "N/A";
                    document.getElementById("sumAssured").innerText =
                        `BDT ${(currentPolicy.SUM_ASSURED || 0).toLocaleString()}`;
                    document.getElementById("installPremium").innerText =
                        `BDT ${(currentPolicy.INSTALL_PREMIUM || 0).toLocaleString()}`;
                    document.getElementById("commencementDate").innerText = currentPolicy.COMMENCEMENT_DATE || "N/A";
                    document.getElementById("dueDate").innerText = currentPolicy.DUE_DATE || "N/A";
                    document.getElementById("dueInstallments").innerText = currentPolicy.DUE_INSTALLMENT || "N/A";
                    document.getElementById("duePremium").innerText =
                        `BDT ${(currentPolicy.DUE_PREMIUM || 0).toLocaleString()}`;

                    policyCard.style.display = "block"; // Show policy details card
                } else {
                    alertMessage.innerText = "No policy data found for the given policy number."; // Set error message
                    alertMessage.style.display = "block"; // Show alert
                    policyCard.style.display = "none"; // Hide policy details card
                }
            } catch (error) {
                console.error("Error fetching policy data:", error);
                alertMessage.innerText = "An unexpected error occurred. Please try again later."; // Set error message
                alertMessage.style.display = "block"; // Show alert
                policyCard.style.display = "none"; // Hide policy details card
            } finally {
                // Restore button state
                searchButton.innerText = "Search";
                searchButton.disabled = false;
            }
        }



        function calculateDuePremium() {
            const installmentCount = parseInt(document.getElementById("dueInstallmentInput").value) || 0;
            const policyNumber = document.getElementById("policyNumber").value.trim();
            const installmentPremium = currentPolicy ? currentPolicy.INSTALL_PREMIUM : 0;
            const totalDuePremium = installmentCount * installmentPremium;
            document.getElementById("duePremiumDisplay").innerText = `BDT ${totalDuePremium.toLocaleString()}`;
            let name = currentPolicy.POLICY_NAME;
            // PayAmount = totalDuePremium;
            initializePaymentButton(totalDuePremium, policyNumber ,currentPolicy, installmentCount);
        }

        function initializePaymentButton(totalDuePremium, policyNumber ,currentPolicy, installmentCount) {


            // Build payment data object
            var obj = {
                cus_name: currentPolicy.POLICY_NAME,
                POLICYNO: policyNumber,
                INSTALL_PREMIUM: currentPolicy.INSTALL_PREMIUM,
                DUE_DATE: currentPolicy.DUE_DATE,
                DUE_INSTALLMENT: currentPolicy.DUE_INSTALLMENT,
                DUE_PREMIUM: currentPolicy.DUE_PREMIUM,
                PAID_INSTALLMENT: installmentCount,
                PAID_AMOUNT: totalDuePremium,
                amount: totalDuePremium,
            };

            console.log("Payment Data:", obj); // Debugging log

            // Check if all required fields are present


            // Assign postdata to the payment button
            $('#sslczPayBtn').prop('postdata', obj);
        }
    </script>
    <script>
        // SSLCommerz script loader
        (function(window, document) {
            var loader = function() {
                var script = document.createElement("script"),
                    tag = document.getElementsByTagName("script")[0];

                // Use sandbox for testing and live for production
                script.src = "https://sandbox.sslcommerz.com/embed.min.js?" + Math.random().toString(36).substring(
                    7);
                // Uncomment below line for live environment
                // script.src = "https://seamless-epay.sslcommerz.com/embed.min.js?" + Math.random().toString(36).substring(7);

                tag.parentNode.insertBefore(script, tag);
            };

            window.addEventListener ?
                window.addEventListener("load", loader, false) :
                window.attachEvent("onload", loader);
        })(window, document);
    </script>
</body>

</html>
<?php /**PATH C:\laragon\www\insurance\resources\views/exampleEasycheckout.blade.php ENDPATH**/ ?>