@extends('layouts.app')
@section('content')
<style>
  button.dt-button, div.dt-button, a.dt-button, input.dt-button {
    border-radius: 5px;
    color: white;
    background-color: rgb(197, 7, 178);
    box-shadow: rgba(50, 50, 93, 0.25) 0px 50px 100px -20px, rgba(0, 0, 0, 0.3) 0px 30px 60px -30px, rgba(10, 37, 64, 0.35) 0px -2px 6px 0px inset;
}

button.dt-button:hover:not(.disabled), div.dt-button:hover:not(.disabled), a.dt-button:hover:not(.disabled), input.dt-button:hover:not(.disabled) {
    border: 1px solid #666;
    background-color: rgb(29, 29, 29);
}

.content form {
        border: 12px solid #f8f8f8;
        background: #f4f4f4;
        padding: 30px 45px 45px;
        margin: 70px 25px 40px;
        border-radius: 5px;
        max-width: 900px;
        box-shadow: 0 1px 7px rgba(0,0,0,0.2);
    }
    .content label {
        display: block;
        font-weight: bold;
        letter-spacing: 0.02em; 
        color: #666;
        text-shadow: 0 0 0 #666;
        padding: 5px 0 8px;
    }
    .content label:not(:first-of-type) {
        margin-top: 30px;
    }
    .content select {   
        width: 100%;
        max-width: 300px;
    }

    /* LC Select - Light theme - by LCweb */


/* container */
.lcslt {
    border: 1px solid #aaa;
    background: #fafafa;
    border-radius: 2px;
    transition: all .25s ease;
    font-size: 15px;
}
.lcslt:not(.lcslt-disabled):hover,
.lcslt.lcslt_dd-open,
#lc-select-dd {
    border-color: #8f8f8f;
    background: #fefefe;
}
.lcslt.lcslt_dd-open {
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}
.lcslt-opt {
    background: #bbb;
    border-radius: 3px;
}
.lcslt:not(.lcslt-multiple):after {
	border-top-color: #888 !important;
}
.lcslt:not(.lcslt-multiple):hover:after,
.lcslt.lcslt_dd-open:not(.lcslt-multiple):after {
	border-top-color: #666 !important;
}
.lcslt:not(.lcslt-multiple) > span {
    padding: 2px 0;
}
.lcslt.lcslt-multiple > span:not(.lcslt-multi-callout) {
    padding: 3px 0 6px;
}
.lcslt:not(.lcslt-multiple) > span:not(.lcslt-placeholder) {
    font-size: 100%;
}
.lcslt > span:not(.lcslt-placeholder):not(.lcslt-multi-callout),
#lc-select-dd li {
    color: #484848;
}


/* disabled status */
.lcslt.lcslt-disabled {
    background: #f4f4f4;
}
.lcslt.lcslt-disabled:not(.lcslt-multiple):after {
	border-top-color: #aaa !important;
}
.lcslt.lcslt-disabled:not(.lcslt-multiple) > span {
    color: #848484;
}
.lcslt.lcslt-disabled .lcslt-multi-selected {
    color: #666;
    padding-left: 9px;
}
.lcslt.lcslt-disabled .lcslt-multi-selected:before {
    display: none;
}


/* multi-option selected items */
.lcslt-multiple {
	font-size: 0.95rem !important;
}
.lcslt-multi-selected,
.lcslt-multi-callout {
    padding: 3px 9px 3px 7px;
    background: #e5e5e5;
    color: #494949;
    border-radius: 50px;
    margin: 0 5px 5px 0;
    transition: all .3s ease;
}
.lcslt-multi-callout {
	padding: 0.75rem 0.4581rem;
	font-family: arial;
	border-radius: 50%;
	font-size: 1rem;
}
.lcslt:not(.lcslt-disabled) .lcslt-multi-selected:hover,
.lcslt:not(.lcslt-disabled) .lcslt-multi-callout:hover {
    background: #ddd;
    color: #3f3f3f; 
}
.lcslt-multi-selected:before {
    padding-right: 6px;
}
.lcslt-placeholder {
	color: #888;
	transform: scale(0.9) translate3d(-5%, -5%, 0);
}


/* dropdown */
#lc-select-dd {
    border-radius: 0 0 4px 4px;
    border-width: 0 1px 1px;
    border-style: solid;
	box-shadow: 0px 3px 3px rgba(0, 0, 0, 0.2);
	font-size: 13px;
    
}
#lc-select-dd li {
    border: none;
    border-top: 1px solid #ddd;
}
.lcslt-search-li {
    border-bottom: 2px dotted #bababa !important;
    box-shadow: 0 1px 0 #fff;
}
.lcslt-search-li input {
	font-size: inherit;
    padding-top: 8px;
    padding-bottom: 8px;
    padding-left: 8px;
    /* font-size: 0.8rem; */
    color: #888;
    background: #fefefe;
}
.lcslt-search-li input:hover,
.lcslt-search-li input:active,
.lcslt-search-li input:focus,
.lcslt-is-searching .lcslt-search-li input {
    color: inherit;
}
.lcslt-search-li:before {
	background: #666;
}
#lc-select-dd li span {
    padding: 7px 12px;
    /* font-size: 0.8rem; */
}
#lc-select-dd li img { 
    padding-right: 7px;
}
.lcslt-group-name {
    font-weight: bold;
}
.lcslt-group-opts > li {
    padding-left: 12px;
}
.lcslt-dd-opt {   
    transition: all .15s ease;
    color: #6f6f6f;
}
#lc-select-dd li.lcslt-dd-opt:not(.lcslt-disabled):not(.lcslt-selected):hover,
#lc-select-dd .lcslt-dd-opt-hlight {  
    color: #333;
    background: #d7eeff;
}
#lc-select-dd li.lcslt-dd-opt.lcslt-disabled {   
    background: #ededed;
    color: #777;
}
#lc-select-dd li.lcslt-selected {   
    color: #fff;
    background: #0078d7;
    text-shadow: 0 0 2px rgba(0,0,0,0.15);
}
#lc-select-dd li.lcslt-selected.lcslt-dd-opt-hlight {
	box-shadow: 6px 0 0 #89caff inset;
}
.lcslt-is-searching li.lcslt-group,
.lcslt-no-results {
    border: none !important;
}
.lcslt-no-results {
    color: #777;
    text-align: center;
    padding: 12px;
}


/* images */
.lcslt-img {
    display: inline-block;
    height: 50px;
    width: 70px;
    margin-right: 20px;
} */
.content-wrapper {
    display: flex;
    justify-content: center; /* Centers horizontally */
    align-items: center;    /* Centers vertically */
           /* Full viewport height */
              /* Full width */
}

.inner-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}

:root{
    --file-container-bg:  #eeeeee;
    --file-bg:  #f8f8f8;
    --file-border-color: #606060;
    --file-rounded: 15px;
    --file-color: #2b2b2b;
    --table-border-color: #dbdbdb;
    --delete-button-bg: #f53636;
    --delete-button-color: #ffffff;
    --font-size: 0.875em;
    --font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    --shadow: 0px 8px 15px -8px rgba(0, 0, 0, 0.5);
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.file-container {
    width: 100%;
    font-family: var(--font-family);

    .file-upload {
        width: 100%;
        display: flex;
        background-color: var(--file-container-bg);
        border-radius: var(--file-rounded);
        transition: all 0.3s;

        &:hover {
            box-shadow: var(--shadow);
        }

        >div {
            width: 100%;
            background-color: var(--file-bg);
            padding: 25px;
            margin: 25px;
            border-radius: 10px;
            border: 1px dashed var(--file-border-color);
            text-align: center;
            cursor: pointer;

            >i {
                font-size: 3.125em;
                color: var(--file-color);
            }

            >p,
            span,
            div {
                font-size: var(--font-size);
                line-height: 30px;
                color: var(--file-color);
            }

            >div {
                width: max-content;
                padding: 0 10px;
                margin: 0 auto;
                border: 1px solid var(--file-border-color);
                border-radius: 8px;
            }
        }
    }

    >table {
        width: 100%;
        border-collapse: collapse;
        font-size: var(--font-size);
        margin-top: 20px;

        & th,
        td {
            border-bottom: 1px solid var(--table-border-color);
            padding: 8px;
            text-align: left;
        }

        >tbody {
            >tr {
                >td {
                    &:nth-child(1) {
                        font-weight: bold;
                    }

                    &:nth-child(2) {
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        max-width: 1px;
                    }

                    &:nth-child(3) {
                        text-align: center;
                    }

                    >img {
                        border-radius: 5px;
                        box-shadow: var(--shadow);
                    }

                    &.no-file {
                        text-align: center;
                        font-weight: normal;
                    }

                    > i{
                        font-size: 1.125em;
                    }
                }
            }
        }

        & button {
            background-color: var(--delete-button-bg);
            width: 30px;
            height: 30px;
            border: none;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;

            &:hover {
                box-shadow: var(--shadow);
            }

            >i {
                color: var(--delete-button-color);
                font-size: 1.125em;
            }
        }
    }
}


</style>
      <!-- partial -->
      <div class="main-panel">
        <div class="content-wrapper">
         
          <div class="row grid-margin">
       
         
          <div class="content-wrapper ">
            <div class="inner-wrapper">
             <div class="col-10 grid-margin stretch-card">
                <div class="card">
                  <div class="card-body">
                    <h4 class="card-title">Basic form elements</h4>
                    <p class="card-description">
                      Basic form elements
                    </p>
                    <form class="forms-sample">
                      <div class="form-group">
                        <label for="exampleInputName1">Title</label>
                        <input type="text" class="form-control" id="title" placeholder="Add Title Here" value="{{$ExpensesData->expenses}}">
                      </div>
                      <div class="form-group">
                        <label for="exampleSelectGender">Select Branch</label>
                        <select name="simple" data-placeholder="Select something please .." id="branch">
                          @foreach ($branches as $branch)
                          <option value="{{ $branch->id }}"
                              {{ $branch->branch_name == $ExpensesData->branch_name ? 'selected' : '' }}>
                              {{-- <option value="{{ $branch->id }}"> --}}
                              {{ $branch->branch_name }}
                          </option>
                      @endforeach
                      </select>
                        </div>
                      <div class="form-group">
                        <label for="exampleInputEmail3">Date</label>
                        <input type="date" class="form-control" id="date" placeholder="Date" value="{{$ExpensesData->date}}">
                      </div>
                      <div class="form-group">
                        <label for="exampleInputPassword4">Time</label>
                        <input type="time" class="form-control" id="time" placeholder="Time" value="{{$ExpensesData->time}}">
                      </div>
                      <div class="form-group">
                        <label for="exampleSelectGender">Select Catecory</label>
                        <select name="simple" data-placeholder="Select something please .." id="Category">
                          @foreach ($ExpensesCategories as $ExpensesCategory)
                          <option value="{{ $ExpensesCategory->id }}"
                              {{ $ExpensesCategory->expenses_category == $ExpensesData->expenses_category ? 'selected' : '' }}>
                              {{-- <option value="{{ $ExpensesCategory->id }}"> --}}
                              {{ $ExpensesCategory->expenses_category }}
                          </option>
                      @endforeach
                      </select>
                        </div>
                      <div class="form-group">
                        <label>Select Sub Catecory</label>
                        <select id="subCategory" name="simple" data-placeholder="Select something please ..">
                            @foreach ($ExpensesSubCategories as $ExpensesSubCategory)
                            <option value="{{ $ExpensesSubCategory->id }}"
                                {{ $ExpensesSubCategory->expenses_sub_category == $ExpensesData->expenses_sub_category ? 'selected' : '' }}>
                                {{-- <option value="{{ $ExpensesCategory->id }}"> --}}
                                {{ $ExpensesSubCategory->expenses_sub_category }}
                            </option>
                        @endforeach
                        </select>
                      </div>
                      <div class="form-group">
                        <label for="exampleInputCity1">Amount</label>
                        <input type="text" class="form-control" id="amount" placeholder="Amount" value="{{$ExpensesData->amount}}">
                      </div>
                      <div class="container">
                        <div class="row">
                          <div class="col-sm form-group">
                            <input type="text" class="form-control" id="item" placeholder="Item Name">
                          </div>
                          <div class="col-sm form-group">
                            <input type="text" class="form-control" id="quantity" placeholder="Quantity">
                          </div>
                          <div class="col-sm form-group">
                            <input type="text" class="form-control" id="itemPrice" placeholder="Item Price">
                          </div>
                        </div>
                        <div class="form-group">
                          <button type="button" class="btn btn-dark" id="adToTable">Add Item</button>
                        </div>
                        <div class="form-group">
                            <table id="itemTable" class="table">
                                <thead>
                                    <tr>
                                        <th>Item Name</th>
                                        <th>Quantity</th>
                                        <th>Item Price</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($ExpensesData->PurchaseItems as $item)
                                        <tr>
                                            <td class='table_font_color'>{{ $item->item_name }}</td>
                                            <td class='table_font_color'>{{ $item->item_quantity }}</td>
                                            <td class='table_font_color'>{{ number_format($item->price, 2) }}</td>
                                            <td><button type='button' class='btn-remove-row'><i class='fa fa-trash menu-icon'></i></button></td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                      
                      </div>
                     
                      <div class="form-group">
                        <label for="exampleTextarea1">Description</label>
                        <textarea class="form-control" id="description" rows="4">{{$ExpensesData->description}}
                        </textarea>
                      </div>
                      <div class="form-group">
                        <label for="exampleTextarea1">Upload Images</label>
                        <div class="parent-div">
                            <div id="fileUpload"></div>
                            
                          </div>
                      </div>

                    
                      <button type="submit" class="btn btn-primary mr-2" id="submit" data-id="{{$ExpensesData->id}}">Submit</button>
                      <button class="btn btn-light">Cancel</button>
                    </form>
                  </div>
                </div>
              </div>
          
            </div>
         </div>
            
        </div>
        <!-- content-wrapper ends -->
        <!-- partial:../../partials/_footer.html -->
        <footer class="footer">
          <div class="d-sm-flex justify-content-center justify-content-sm-between">
            <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Copyright © 2025  <a href="https://www.urbanui.com/" target="_blank">Urbanui</a>. All rights reserved.</span>
            <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">Hand-crafted & made with <i class="far fa-heart text-danger"></i></span>
          </div>
        </footer>
        <!-- partial -->
      </div>
      
     
      <script>

        
$( document ).ready(function() {

    var serverFiles = [];

@foreach ($ExpensesData->Expenses_images as $index => $image)
    serverFiles.push({
        name: "{{ $image->image_name }}",
        url: "{{ asset('assets/Expenses/' . $image->image_name) }}",
        size: "--",
        type: "{{ pathinfo($image->image_name, PATHINFO_EXTENSION) }}",
        id: "{{ $image->id }}",
        server: true // Flag to indicate it's a server-side image
    });
@endforeach
  
(function ($) {
    var fileUploadCount = 0;

    $.fn.fileUpload = function () {
        return this.each(function () {
            var fileUploadDiv = $(this);
            var fileUploadId = `fileUpload-${++fileUploadCount}`;
            var fileList = fileUploadDiv.data("fileList") || [];

            // Create HTML content for the file upload area
            var fileDivContent = `
                <label for="${fileUploadId}" class="file-upload">
                    <div>
                        <p>Drag & Drop Files Here</p>
                        <span>OR</span>
                        <div>Browse Files</div>
                    </div>
                    <input type="file" id="${fileUploadId}" name="expensesImages[]" multiple hidden />
                </label>
            `;

            fileUploadDiv.html(fileDivContent).addClass("file-container");

            var table = null;
            var tableBody = null;

            // Create a table containing file information
            function createTable() {
                table = $(`
                    <table>
                        <thead>
                            <tr>
                                <th></th>
                                <th style="width: 30%;">File Name</th>
                                <th>Preview</th>
                                <th style="width: 20%;">Size</th>
                                <th>Type</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                `);
                tableBody = table.find("tbody");
                fileUploadDiv.append(table);
            }

            // Handle uploaded files
            function handleFiles(files) {
                if (!table) {
                    createTable();
                }

                fileList = Array.from(files);
                fileUploadDiv.data("fileList", fileList);
                updateTable(fileList);
            }

            // Update the table with the current files in fileList
            function updateTable(fileList) {
                tableBody.empty();

                // Combine server-side images and uploaded files
                let allFiles = [...serverFiles];

                if (fileList.length > 0) {
                    $.each(fileList, function (index, file) {
                        allFiles.push({
                            name: file.name,
                            url: URL.createObjectURL(file),
                            size: (file.size / 1024).toFixed(2) + " KB",
                            type: file.type,
                            server: false // Flag to indicate it's an uploaded file
                        });
                    });
                }

                // Render the combined list of files
                $.each(allFiles, function (index, file) {
                    tableBody.append(`
                        <tr data-file-index="${index}">
                            <td>${index + 1}</td>
                            <td>${file.name}</td>
                            <td>
                                <img src="${file.url}" alt="${file.name}" height="30">
                            </td>
                            <td>${file.size}</td>
                            <td>${file.type}</td>
                            <td>
                                <button type="button" class="deleteBtn" ${file.server ? `data-image-id="${file.id}"` : ''}>
                                    <i class="fa fa-trash menu-icon"></i>
                                </button>
                            </td>
                        </tr>
                    `);
                });

                // Handle delete button for uploaded files
                tableBody.find(".deleteBtn").click(function () {
                    var row = $(this).closest("tr");
                    var fileIndex = row.data("file-index");

                    if (allFiles[fileIndex].server) {
                        // Handle server-side image deletion
                        var imageId = $(this).data("image-id");
                  
                        $.ajax({
                            url: "{{ route('delete-images') }}",
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
                            type: 'POST',
                            data: {'id':imageId},
                            success: function (response) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success',
                                    text: 'Your image deleted successfully!',
                                    confirmButtonText: 'OK',
                                }).then((result) => {
                                if (result.isConfirmed) {
                                    window.location.reload();
                                }
                                });
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                alert('Form submission failed!');
                            }
                        });
                    } else {
                        // Handle uploaded file deletion
                        fileList.splice(fileIndex - serverFiles.length, 1);
                        fileUploadDiv.data("fileList", fileList);
                    }

                    updateTable(fileList);

                    if (fileList.length === 0) {
                        tableBody.append(
                            '<tr><td colspan="6" class="no-file">No files selected!</td></tr>'
                        );
                    }
                    updateFileInput(fileUploadId, fileList);
                });

                // If no files are present, show a placeholder message
                if (allFiles.length === 0) {
                    tableBody.append(
                        '<tr><td colspan="6" class="no-file">No files selected!</td></tr>'
                    );
                }
            }

            // Update the file input with the current fileList
            function updateFileInput(fileUploadId, fileList) {
                var dataTransfer = new DataTransfer();
                fileList.forEach((file) => dataTransfer.items.add(file));
                document.getElementById(fileUploadId).files = dataTransfer.files;
            }

            // Events triggered after dragging files
            fileUploadDiv.on({
                dragover: function (e) {
                    e.preventDefault();
                    fileUploadDiv.toggleClass("dragover", e.type === "dragover");
                },
                drop: function (e) {
                    e.preventDefault();
                    fileUploadDiv.removeClass("dragover");
                    handleFiles(e.originalEvent.dataTransfer.files);
                },
            });

            // Event triggered when file is selected
            fileUploadDiv.find(`#${fileUploadId}`).change(function () {
                handleFiles(this.files);
            });

            // Initialize the table with server-side images
            if (serverFiles.length > 0) {
                if (!table) {
                    createTable();
                }
                updateTable([]);
            }
        });
    };

    // Initialize the file upload plugin on document ready
    $(document).ready(function () {
        $(".file-upload-container").fileUpload();
    });
})(jQuery);




  var mortgageDataArray = []; 
  // Create an empty array to store the mortgage data
  var rowData = '';

  @foreach ($ExpensesData->PurchaseItems as $item)
        mortgageDataArray.push({
            item: "{{ $item->item_name }}",
            quantity: "{{ $item->item_quantity }}",
            itemPrice: "{{ number_format($item->price, 2) }}"
        });
    @endforeach

$("#adToTable").click(function() {
    
    var item = $("#item").val();
    var quantity = $("#quantity").val(); // Assuming you have this field for gold items
    var itemPrice = $("#itemPrice").val();


        rowData = {
          item: item,
          quantity: quantity, // Add mortgageSubType to the rowData object
          itemPrice: itemPrice,
      
        };

        // Push the selected images into the images array of the rowData object
      
        // Push the rowData object into the mortgageDataArray
        mortgageDataArray.push(rowData);

        // Create a new row in the table with a "Remove" button
        if ($("#itemTable tbody tr").length === 0) {
            $("#itemTable tbody").append(
                "<tr style='background-color: #1F305E; color: white;'><th >Item Name</th><th>Quantity</th><th>Item Price</th><th>Action</th></tr>"
            );
        }
        var newRow = "<tr><td class='table_font_color'>" + item +
            "</td><td class='table_font_color'>" + quantity + 
            "</td><td class='table_font_color'>" + itemPrice + "</td>";

            newRow +=
            "<td><button type='button' class='btn-remove-row'> <i class='fa fa-trash menu-icon'></i></button></td></tr>";
        $("#itemTable tbody").append(newRow);
    

    // Reset the dropdowns and fields to their initial state
    // $("#Mortgage_Type").val("");
    $("#itemPrice").val("");
    $("#quantity").val("");
    $("#item").val("");

});




  $(document).on("click", ".btn-remove-row", function() {
            var rowIndex = $(this).closest("tr").index();
            mortgageDataArray.splice(rowIndex, 1); // Remove the corresponding data from the array
            $(this).closest("tr").remove();
        });
 
    $("#fileUpload").fileUpload();

    new lc_select(document.querySelector('#Category'), {
        wrap_width: '100%',
        min_for_search: 2,
        pre_placeh_opt: true,
    });
    new lc_select(document.querySelector('#subCategory'), {
        wrap_width: '100%',
        min_for_search: 2,
        pre_placeh_opt: true,
    });
    new lc_select(document.querySelector('#branch'), {
        wrap_width: '100%',
        min_for_search: 2,
        pre_placeh_opt: true,
    });
    

    $(document).on('change','#Category', function(){
      
            var id = $('#Category').val();
 
            $.ajax({
                url: "{{ route('get-expenses-sub-categories') }}",
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                data: {'id':id},
            
                success: function(data) {
                 // Assuming data.data is an array of { id, name } for sub-categories
                    $('#subCategory').empty();  // Clear existing options
                    $('#subCategory').append('<option value="">Select Sub Category</option>');
                    $.each(data.data, function(index, subCategory) {
                    $('#subCategory').append('<option value="' + subCategory.id + '">' + subCategory.expenses_sub_category + '</option>');
                });
            },
                error: function(xhr, textStatus, errorThrown) {
                    alert('Form submission failed!');
                }
            });
        })
  // alert("hi")

  // $(document).on('click','#submit', function(e){
  //   e.preventDefault();
  //   var expensesImages = $('input[name="expensesImages[]"]').prop('files');
  //   if (expensesImages.length > 0) {
  //       // Iterate over the FileList and alert each file name
  //       for (var i = 0; i < expensesImages.length; i++) {
  //           alert(expensesImages[i].name);
  //       }
  //   } else {
  //       alert("No files selected.");
  //   }
  // })

  $(document).on("click", "#submit", function (e) {
        e.preventDefault();
        var fileUploadDiv = $(".file-container"); // Assuming there's only one file upload container
        var fileList = fileUploadDiv.data("fileList") || [];
        var title =$('#title').val();
        var description =$('#description').val();
        var expenses_id = $(this).data("id");
        var branch =$('#branch').val();
        var date =$('#date').val();
        var time =$('#time').val();
        var Category =$('#Category').val();
        var subCategory =$('#subCategory').val();
        var amount =$('#amount').val();

        var isValid = true;
            var errorMessage = '';

            // Perform individual validation checks for each input field
        if (!date || date.length === 0) {
            errorMessage += 'Date is required.<br>';
            isValid = false;
        }
        if (!Category || Category.length === 0) {
            errorMessage += 'Category is required.<br>';
            isValid = false;
        }
        if (!subCategory || subCategory.length === 0) {
            errorMessage += 'Sub Category is required.<br>';
            isValid = false;
        }
        if (!amount || amount.length === 0) {
            errorMessage += 'Amount is required.<br>';
            isValid = false;
        }
        if (!branch || branch.length === 0) {
            errorMessage += 'Branch is required.<br>';
            isValid = false;
        }
        if (!isValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errorMessage,
                    showCloseButton: true,
                    showCancelButton: false,
                    focusConfirm: false,
                    confirmButtonText: 'OK',
                });
                return;
      }else{
        var form_data = new FormData();
            form_data.append('_token', '{{ csrf_token() }}');
            form_data.append('branchId', branch);
            form_data.append('expenses_id', expenses_id);
            
            form_data.append('title', title);
            form_data.append('date', date);
            form_data.append('time', time);
            form_data.append('amount', amount);
            form_data.append('Category', Category);
            form_data.append('subCategory', subCategory);
            form_data.append('description', description);

            $.each(mortgageDataArray, function(i, rowData) {
              form_data.append('mortgageData[' + i + '][item]', rowData.item);
              form_data.append('mortgageData[' + i + '][quantity]', rowData.quantity);
              form_data.append('mortgageData[' + i + '][itemPrice]', rowData.itemPrice); // Append mortgageSubType
            });
            $.each(fileList, function (i, file) {
                form_data.append('expensesImages[]', file);
            });

            serverFiles.forEach(function (file) {
        form_data.append('existingImages[]', file.id);
    });

            $.ajax({
                url: '/update-expenses', // Replace with your backend URL
                type: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Your data has been submitted successfully!',
                        confirmButtonText: 'OK',
                    }).then((result) => {
                      if (result.isConfirmed) {
                         window.location.reload();
                      }
                    });
                },
                error: function (response) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'There was an error submitting your data.',
                        confirmButtonText: 'OK',
                    });
                }
            });
      }
              
    });
  


  $('#example').DataTable({
            dom: "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ],
            processing: true,
            info: true,
            responsive: true,
            lengthMenu: [
                [10, 25, 50, 100, 200, -1],
                [10, 25, 50, 100, 200, "All"]
            ],


           
            createdRow: function(row, data, dataIndex) {
            // Example condition to change font color
            // Adjust condition as needed
                $(row).css('font-size', '15px');
           
        }
        });
});
      
      </script>
@endsection
      <!-- main-panel ends -->
    