<?php include 'header.php'; ?>

<style>
    .role-dropdown {
        left: 15px;
        width: 92% !important;
    }
</style>
<style>
    .is-invalid {
        border: 1px solid red !important;
    }

    .error-text {
        font-size: 13px;
    }

    #singleDate.is-invalid {
        background-image: none !important;
    }

    .gst-radio-group {
        display: flex;
        align-items: center;
        gap: 30px;
        margin-top: 8px;
    }

    .gst-radio-group .form-check {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0;
        padding: 0;
    }

    .gst-radio-group .form-check-input {
        margin: 0;
        cursor: pointer;
    }

    .gst-radio-group .form-check-label {
        margin: 0;
        cursor: pointer;
        font-size: 15px;
    }
</style>

<div class="dashboard-main-body">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
        <h6 class="fw-semibold mb-0">Add Expense Management</h6>
    </div>
    <div class="d-flex flex-wrap align-items-center justify-content-end gap-3 mb-3">
        <a type="button" href="expense_manage.php"
            class="tooltip-button btn bg-primary-600 text-white border border-primary-600 radius-8 px-12 py-11 d-flex align-items-center"
            data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true" data-bs-custom-class="tooltip-primary"
            title="Listing">
            <iconify-icon icon="ic:baseline-arrow-back" class="icon text-xl line-height-1"></iconify-icon>
        </a>
    </div>

    <div class="row gy-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <h6 class="mb-4 text-xl">Add Expense Management</h6> <br />
                    <form id="modelform" action="" method="post">
                        <div class="row gy-3">
                            <div class="col-sm-4">
                                <label class="form-label">Expense Date<span class="text-danger">*</span></label>
                                <input type="text" id="singleDate" class="form-control" placeholder="dd-mm-yyyy"
                                    readonly />
                            </div>
                            <div class="col-sm-4">
                                <label class="form-label">
                                    Payment Date <span class="text-danger">*</span>
                                </label>

                                <input type="text" id="paymentDate" name="payment_date" class="form-control"
                                    placeholder="dd-mm-yyyy" readonly />
                            </div>
                            <div class="col-sm-4 position-relative">
                                <label class="form-label">Expense Category<span class="text-danger">*</span></label>
                                <input type="text" placeholder="Search for Expense Category"
                                    class="form-control dropdown-search" autocomplete="off" />
                                <ul id="roleDropdown" class="role-dropdown">
                                    <li>Cleaning</li>
                                    <li>Electricity</li>
                                    <li>Other</li>
                                    <li>Repair & Maintenance</li>
                                </ul>
                            </div>
                            <div class="col-sm-4">
                                <label class="form-label">Amount<span class="text-danger">*</span></label>
                                <input type="number" name="amount" class="form-control" placeholder="Enter Amount"
                                    value="" />
                            </div>
                            <div class="col-sm-4 position-relative">
                                <label class="form-label">Payment Mode<span class="text-danger">*</span></label>
                                <input type="text" placeholder="Search for Payment Mode"
                                    class="form-control dropdown-search" autocomplete="off" />
                                <ul id="roleDropdown" class="role-dropdown">
                                    <li>Cash</li>
                                    <li>UPI</li>
                                    <li>Cheque</li>
                                </ul>
                            </div>
                            <div class="col-sm-4">
                                <label class="form-label">Paid To<span class="text-danger">*</span></label>
                                <input type="text" name="paidto" class="form-control" placeholder="Enter Paid To"
                                    value="" />
                            </div>
                            <div class="col-sm-4">
                                <label class="form-label">Remark</label>
                                <input type="text" name="remark" class="form-control" placeholder="Enter Remark"
                                    value="" />
                            </div>

                            <div class="col-sm-4">
                                <label class="form-label">Vendor Name<span class="text-danger">*</span></label>
                                <input type="text" name="vendor_name" class="form-control"
                                    placeholder="Enter Vendor Name" />
                            </div>

                            <div class="col-sm-4">
                                <label class="form-label d-block mb-2">
                                    GST Registered?
                                </label>

                                <div class="gst-radio-group">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="has_gst" id="gstYes"
                                            value="Yes">

                                        <label class="form-check-label" for="gstYes">
                                            Yes
                                        </label>
                                    </div>

                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="has_gst" id="gstNo"
                                            value="No" checked>

                                        <label class="form-check-label" for="gstNo">
                                            No
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <!-- GST Number -->
                            <div class="col-sm-4" id="gstBox" style="display:none;">
                                <label class="form-label">
                                    GST Number
                                </label>

                                <input type="number" name="gst" class="form-control" placeholder="Enter Number" min="0"
                                    max="100">
                            </div>

                            <div class="col-sm-4">
                                <label class="form-label">Upload Invoice<span class="text-danger">*</span></label>

                                <input type="file" name="invoice" class="form-control" id="invoiceInput"
                                    accept="image/*" />

                                <!-- Image Preview -->
                                <div class="mt-3 d-none" id="previewContainer">
                                    <img id="invoicePreview" src="" alt="Invoice Preview"
                                        style="width: 120px; height: 120px; object-fit: cover; border-radius: 10px; border:1px solid #ddd;">
                                </div>
                            </div>
                            <div class="form-group text-end mt-4">
                                <button type="submit" class="btn btn-primary-600 px-32">
                                    <i class="bi bi-floppy"></i>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!--VALIDATION SCRITP-->
<script>
    document.getElementById("modelform").addEventListener("submit", function (e) {

        e.preventDefault();

        // Remove old validation
        document.querySelectorAll(".form-control").forEach(el => {
            el.classList.remove("is-invalid");
        });

        // Fields
        const expenseDate = document.getElementById("singleDate");

        const dropdowns = document.querySelectorAll(".dropdown-search");

        const expenseCategory = dropdowns[0];
        const paymentMode = dropdowns[1];
        const paymentDate = document.getElementById("paymentDate");

        const amount = document.querySelector('input[name="amount"]');
        const paidto = document.querySelector('input[name="paidto"]');
        const shorttitle = document.querySelector('input[name="shorttitle"]');
        const description = document.querySelector('textarea[name="description"]');
        const vendor = document.querySelector('input[name="vendor_name"]');

        const invoice = document.getElementById('invoiceInput');

        // Sweet Alert Function
        function showAlert(input, message) {

            input.classList.add("is-invalid");
            input.focus();

            Swal.fire({
                icon: 'warning',
                title: 'Required Field',
                text: message,
                confirmButtonColor: '#2563eb',
                confirmButtonText: 'OK',
                width: '350px',
                padding: '15px',
                customClass: {
                    popup: 'swal-modern',
                    title: 'swal-title',
                    htmlContainer: 'swal-text',
                    confirmButton: 'swal-confirm',
                    cancelButton: 'swal-cancel'
                }
            });

        }

        // Expense Date
        if (expenseDate.value.trim() === "") {
            showAlert(expenseDate, "Please Select Expense Date");
            return;
        }

        // Expense Category
        if (expenseCategory.value.trim() === "") {
            showAlert(expenseCategory, "Please Select Expense Category");
            return;
        }

        // Amount
        if (amount.value.trim() === "") {

            showAlert(amount, "Please Enter Amount");
            return;

        } else if (parseFloat(amount.value) <= 0) {

            showAlert(
                amount,
                "Invalid Amount",
                "Amount must be greater than 0"
            );

            return;
        }

        // Payment Mode
        if (paymentMode.value.trim() === "") {
            showAlert(paymentMode, "Please Select Payment Mode");
            return;
        }

        // Paid To
        if (paidto.value.trim() === "") {
            showAlert(paidto, "Please Enter Paid To");
            return;
        }

        if (paymentDate.value.trim() === "") {

            showAlert(paymentDate, "Please Select Payment Date");

            return;
        }

        // Short Title
        if (shorttitle.value.trim() === "") {
            showAlert(shorttitle, "Please Enter Expense Short Title");
            return;
        }

        // Description
        if (description.value.trim() === "") {
            showAlert(description, "Please Enter Description");
            return;
        }

        // Vendor Name
        if (vendor.value.trim() === "") {
            showAlert(vendor, "Please Enter Vendor Name");
            return;
        }

        // Invoice Validation
        if (invoice.files.length === 0) {

            showAlert(invoice, "Please Upload Invoice");
            return;

        } else {

            const file = invoice.files[0];

            const allowedTypes = [
                "image/jpeg",
                "image/png",
                "image/jpg",
                "image/webp"
            ];

            // File Type
            if (!allowedTypes.includes(file.type)) {

                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Image Format',
                    text: 'Only JPG, PNG & WEBP allowed',
                    confirmButtonColor: '#dc2626',
                    width: '350px',
                    padding: '15px',
                    customClass: {
                        popup: 'swal-modern',
                        title: 'swal-title',
                        htmlContainer: 'swal-text',
                        confirmButton: 'swal-confirm',
                        cancelButton: 'swal-cancel'
                    }
                });

                return;
            }

            // File Size
            if (file.size > 2 * 1024 * 1024) {

                Swal.fire({
                    icon: 'error',
                    title: 'Image Too Large',
                    text: 'Maximum image size is 2MB',
                    confirmButtonColor: '#dc2626',
                    width: '350px',
                    padding: '15px',
                    customClass: {
                        popup: 'swal-modern',
                        title: 'swal-title',
                        htmlContainer: 'swal-text',
                        confirmButton: 'swal-confirm',
                        cancelButton: 'swal-cancel'
                    }
                });

                return;
            }
        }

        // Success Alert
        Swal.fire({
            icon: 'success',
            title: 'Validated Successfully',
            text: 'Expense added successfully',
            confirmButtonColor: '#16a34a',
            width: '350px',
            padding: '15px',
            customClass: {
                popup: 'swal-modern',
                title: 'swal-title',
                htmlContainer: 'swal-text',
                confirmButton: 'swal-confirm',
                cancelButton: 'swal-cancel'
            }
        }).then(() => {

            e.target.submit();

        });

    });
</script>

<!-- Role Dropdown Search & Selection -->
<script>
    document.addEventListener("DOMContentLoaded", function () {

        const dropdownInputs = document.querySelectorAll(".dropdown-search");

        dropdownInputs.forEach(function (input) {

            const dropdown = input.nextElementSibling;
            const items = dropdown.querySelectorAll("li");

            function showDropdown() {
                dropdown.style.display = "block";
            }

            function hideDropdown() {
                dropdown.style.display = "none";
            }

            input.addEventListener("focus", showDropdown);
            input.addEventListener("click", showDropdown);

            input.addEventListener("input", function () {

                let value = this.value.toLowerCase();

                items.forEach(function (item) {

                    if (item.textContent.toLowerCase().includes(value)) {
                        item.style.display = "block";
                    } else {
                        item.style.display = "none";
                    }

                });

            });

            items.forEach(function (item) {

                item.addEventListener("click", function () {

                    input.value = this.textContent;
                    hideDropdown();

                });

            });

            document.addEventListener("click", function (e) {

                if (!input.contains(e.target) && !dropdown.contains(e.target)) {
                    hideDropdown();
                }

            });

        });

    });
</script>

<!--date picker-->
<script src="https://cdn.jsdelivr.net/npm/litepicker/dist/bundle.js"></script>
<!--date picker-->
<script>
    new Litepicker({
        element: document.getElementById('singleDate'),
        singleMode: true,
        format: 'DD-MM-YYYY',

        // ✅ month & year popup enabled
        dropdowns: {
            months: true,
            years: true
        }
    });
</script>

<script>

    new Litepicker({
        element: document.getElementById('paymentDate'),
        singleMode: true,
        format: 'DD-MM-YYYY',

        dropdowns: {
            months: true,
            years: true
        }
    });

</script>


<script>
    document.getElementById('invoiceInput').addEventListener('change', function (event) {

        const file = event.target.files[0];
        const preview = document.getElementById('invoicePreview');
        const previewContainer = document.getElementById('previewContainer');

        if (file) {

            const reader = new FileReader();

            reader.onload = function (e) {
                preview.src = e.target.result;
                previewContainer.classList.remove('d-none');
            }

            reader.readAsDataURL(file);

        }

    });
    document.addEventListener("DOMContentLoaded", function () {

        const gstYes = document.getElementById("gstYes");
        const gstNo = document.getElementById("gstNo");
        const gstBox = document.getElementById("gstBox");

        gstYes.addEventListener("change", function () {

            if (this.checked) {
                gstBox.style.display = "block";
            }

        });

        gstNo.addEventListener("change", function () {

            if (this.checked) {
                gstBox.style.display = "none";

                document.querySelector('input[name="gst"]').value = '';
            }

        });

    });
</script>

<?php include 'footer.php'; ?>