@extends('layouts.app')

@section('title', 'Campaign Create')

@section('content')
    <!-- [ page-header ] start -->
    <form id="createCampaignForm" method="POST" action="/campaigns/store">
        @csrf
        <div class="page-header">
            <div class="page-header-left d-flex align-items-center">
                <div class="page-header-title">
                    <h5 class="m-b-10">Campaign</h5>
                </div>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('index') }}">Home</a></li>
                    <li class="breadcrumb-item">Create</li>
                </ul>
            </div>
            <div class="page-header-right ms-auto">
                <div class="page-header-right-items">
                    <div class="d-flex d-md-none">
                        <a href="javascript:void(0)" class="page-header-right-close-toggle">
                            <i class="feather-arrow-left me-2"></i>
                            <span>Back</span>
                        </a>
                    </div>
                    <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                        <a href="javascript:void(0);" class="btn btn-light-brand successAlertMessage">
                            <i class="feather-layers me-2"></i>
                            <span>Save as Draft</span>
                        </a>
                        <a href="javascript:void(0);" class="btn btn-primary successAlertMessage"
                            onclick="document.getElementById('createCampaignForm').submit();">
                            <i class="feather-user-plus me-2"></i>
                            <span>Create Campaign</span>
                        </a>
                    </div>
                </div>
                <div class="d-md-none d-flex align-items-center">
                    <a href="javascript:void(0)" class="page-header-right-open-toggle">
                        <i class="feather-align-right fs-20"></i>
                    </a>
                </div>
            </div>
        </div>
        <!-- [ page-header ] end -->
        <!-- [ Main Content ] start -->
        <div class="main-content">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-top-0">
                        {{-- <div class="card-header p-0">
                                <!-- Nav tabs -->
                                <ul class="nav nav-tabs flex-wrap w-100 text-center customers-nav-tabs" id="myTab"
                                    role="tablist">
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link active" data-bs-toggle="tab"
                                            data-bs-target="#profileTab" role="tab">Profile</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#passwordTab" role="tab">Password</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#billingTab" role="tab">Billing & Shipping</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#subscriptionTab" role="tab">Subscription</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#notificationsTab" role="tab">Notifications</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#connectionTab" role="tab">Connection</a>
                                    </li>
                                </ul>
                            </div> --}}


                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="profileTab" role="tabpanel">
                                <div class="card-body personal-info">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0 me-4">
                                            <span class="d-block mb-2">Campaign Information:</span>
                                        </h5>
                                    </div>
                                    {{-- <div class="row mb-4 align-items-center">
                                                <div class="col-lg-4">
                                                    <label class="fw-semibold">Avatar: </label>
                                                </div>
                                                <div class="col-lg-8">
                                                    <div class="mb-4 mb-md-0 d-flex gap-4 your-brand">
                                                        <div
                                                            class="wd-100 ht-100 position-relative overflow-hidden border border-gray-2 rounded">
                                                            <img src="assets/images/avatar/1.png"
                                                                class="upload-pic img-fluid rounded h-100 w-100"
                                                                alt="">
                                                            <div
                                                                class="position-absolute start-50 top-50 end-0 bottom-0 translate-middle h-100 w-100 hstack align-items-center justify-content-center c-pointer upload-button">
                                                                <i class="feather feather-camera"
                                                                    aria-hidden="true"></i>
                                                            </div>
                                                            <input class="file-upload" type="file" accept="image/*">
                                                        </div>
                                                        <div class="d-flex flex-column gap-1">
                                                            <div class="fs-11 text-gray-500 mt-2"># Upload your prifile
                                                            </div>
                                                            <div class="fs-11 text-gray-500"># Avatar size 150x150</div>
                                                            <div class="fs-11 text-gray-500"># Max upload size 2mb</div>
                                                            <div class="fs-11 text-gray-500"># Allowed file types: png,
                                                                jpg, jpeg</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div> --}}

                                    <div class="row">
                                        @php
                                            $selectedContactId = request('id');
                                        @endphp

                                        <!-- <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Select Contact: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="contact_id" id="contact-dropdown"
                                                    {{ $selectedContactId ? 'disabled' : '' }}>
                                                    {{-- Disable if `id` is passed --}}
                                                    <option value="" disabled
                                                        {{ !$selectedContactId ? 'selected' : '' }}>Select
                                                        Contact
                                                    </option>
                                                    @foreach ($contacts as $contact)
                                                        <option value="{{ $contact->id }}"
                                                            {{ $selectedContactId == $contact->id ? 'selected' : '' }}>
                                                            {{ $contact->first_name }}
                                                        </option>
                                                    @endforeach
                                                </select>

                                                @if ($selectedContactId)
                                                    <input type="hidden" name="contact_id"
                                                        value="{{ $selectedContactId }}">
                                                @endif
                                            </div>
                                        </div> -->




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="campaignNameInput" class="fw-semibold">Campaign
                                                    Name:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-tag"></i>
                                                    </div>
                                                    <input type="text" class="form-control" name="campaign_name"
                                                        id="campaignNameInput" placeholder="Campaign Name">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="campaignCodeInput" class="fw-semibold">Campaign
                                                    Code:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-hash"></i>
                                                    </div>
                                                    <input type="text" class="form-control" name="campaign_code"
                                                        id="campaignCodeInput" placeholder="Campaign Code">
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Currency: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-dollar-sign"></i></div>
                                                    <select class="form-control" name="currency" id="currency-dropdown">
                                                        <option value="">Select Currency</option>
                                                        <option value="1">USD - United States Dollar</option>
                                                        <option value="2">EUR - Euro</option>
                                                        <option value="3">GBP - British Pound</option>
                                                        <option value="4">INR - Indian Rupee</option>
                                                        <option value="5">JPY - Japanese Yen</option>
                                                        <option value="6">AUD - Australian Dollar</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Campaign Type:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-type"></i></div>
                                                    <select class="form-control" name="campaign_type"
                                                        id="campaign-type-dropdown">
                                                        <option value="1">New Business</option>
                                                        <option value="2">Existing Business</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="expectedRevenueInput" class="fw-semibold">Expected
                                                    Revenue:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-dollar-sign"></i>
                                                    </div>
                                                    <input type="number" class="form-control" name="expected_revenue"
                                                        id="expectedRevenueInput" placeholder="Expected Revenue">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="budgetedCostInput" class="fw-semibold">Budgeted
                                                    Cost:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-dollar-sign"></i>
                                                    </div>
                                                    <input type="number" class="form-control" name="budgeted_cost"
                                                        id="budgetedCostInput" placeholder="Budgeted Cost">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="actualCostInput" class="fw-semibold">Actual
                                                    Cost:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-dollar-sign"></i>
                                                    </div>
                                                    <input type="number" class="form-control" name="actual_cost"
                                                        id="actualCostInput" placeholder="Actual Cost">
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="expectedResponseInput" class="fw-semibold">Expected
                                                    Response:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-message-circle"></i>
                                                    </div>
                                                    <input type="text" class="form-control" name="expected_response"
                                                        id="expectedResponseInput" placeholder="Expected Response">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="proposedStartDate" class="fw-semibold">Proposed
                                                    Start
                                                    Date:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-calendar"></i>
                                                    </div>
                                                    <input type="date" class="form-control" name="proposed_start_date"
                                                        id="proposedStartDate" placeholder="Pick proposed start date"
                                                        required>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="proposedEndDate" class="fw-semibold">Proposed End
                                                    Date:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-calendar"></i>
                                                    </div>
                                                    <input type="date" class="form-control" name="proposed_end_date"
                                                        id="proposedEndDate" placeholder="Pick proposed end date"
                                                        required>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="actualStartDate" class="fw-semibold">Actual Start
                                                    Date:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-calendar"></i>
                                                    </div>
                                                    <input type="date" class="form-control" name="actual_start_date"
                                                        id="actualStartDate" placeholder="Pick actual start date"
                                                        required>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="actualEndDate" class="fw-semibold">Actual End
                                                    Date:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-calendar"></i>
                                                    </div>
                                                    <input type="date" class="form-control" name="actual_end_date"
                                                        id="actualEndDate" placeholder="Pick actual end date" required>
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="numberSentInput" class="fw-semibold">Number
                                                    Sent:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-send"></i>
                                                    </div>
                                                    <input type="number" class="form-control" name="number_sent"
                                                        id="numberSentInput" placeholder="Number Sent">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="descriptionInput" class="fw-semibold">Description:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                                    <textarea class="form-control" name="description" id="descriptionInput" placeholder="Enter description"
                                                        rows="3"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="templateInput" class="fw-semibold">Template:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-layout"></i>
                                                    </div>
                                                    <textarea class="form-control" name="template" id="templateInput" placeholder="Enter template content"
                                                        rows="3"></textarea>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Owner: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                                    <select class="form-control" name="owner" id="contact-owner-dropdown">
                                                        <option value="" disabled>Select Owner</option>
                                                        @foreach ($users as $user)
                                                            <option value="{{ $user->id }}"
                                                                {{ auth()->id() == $user->id ? 'selected' : '' }}>
                                                                {{ $user->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Status: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="status"
                                                    data-select2-selector="status" required>
                                                    <option value="Proposed" data-bg="bg-info" selected>
                                                        Proposed
                                                    </option>
                                                    <option value="Ready to Launch" data-bg="bg-primary">Ready
                                                        to
                                                        Launch</option>
                                                    <option value="Launched" data-bg="bg-success">Launched
                                                    </option>
                                                    <option value="Completed" data-bg="bg-secondary">Completed
                                                    </option>
                                                    <option value="Cancelled" data-bg="bg-warning">Cancelled
                                                    </option>
                                                    <option value="Suspended" data-bg="bg-danger">Suspended
                                                    </option>
                                                </select>
                                            </div>
                                        </div>

                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>
        <div class="card mx-4 mb-4"><div class="card-header"><h5>Audience & Results</h5></div><div class="card-body"><div class="row">
            <div class="col-md-6 mb-3"><label class="form-label">Actual Revenue</label><input class="form-control" type="number" step=".01" min="0" name="actual_revenue"></div>
            <div class="col-md-6 mb-3"><label class="form-label">Lead Source</label><input class="form-control" name="lead_source" placeholder="Facebook, Mailchimp, Referral..."></div>
            <div class="col-md-4 mb-3"><label class="form-label">Target Leads</label><select class="form-control" name="lead_ids[]" multiple size="6">@foreach($leads as $lead)<option value="{{ $lead->id }}">{{ $lead->first_name }} {{ $lead->last_name }}</option>@endforeach</select></div>
            <div class="col-md-4 mb-3"><label class="form-label">Target Contacts</label><select class="form-control" name="contact_ids[]" multiple size="6">@foreach($contacts as $contact)<option value="{{ $contact->id }}">{{ $contact->first_name }} {{ $contact->last_name }}</option>@endforeach</select></div>
            <div class="col-md-4 mb-3"><label class="form-label">Target Customers</label><select class="form-control" name="customer_ids[]" multiple size="6">@foreach($contacts->filter(fn($c)=>strtolower((string)$c->type)==='customer') as $contact)<option value="{{ $contact->id }}">{{ $contact->first_name }} {{ $contact->last_name }}</option>@endforeach</select></div>
        </div></div></div>
    </form>
    <!-- [ Main Content ] end -->
@endsection

@section('scripts')

    <script>
        function productformat(t) {
            var e = t.element;
            return $(
                '<span class="hstack gap-3"> ' +
                t.text +
                "</span>"
            );
        }

        $(document).ready(function() {
            $("[data-select2-selector='product']").select2({
                theme: "bootstrap-5",
                templateResult: productformat,
                templateSelection: productformat
            });
        });
    </script>
    <script>
        function addPhoneField() {
            const newPhoneRow = `
        <div class="row align-items-center mb-2 phone-row">
            <div class="col-md-12">
                <div class="input-group">
                    <div class="input-group-text">
                        <i class="feather-phone"></i>
                    </div>
                    <select class="form-control w-auto" name="phone_types[]">
                        <option value="1">Mobile</option>
                        <option value="2">Home</option>
                        <option value="3">Work</option>
                        <option value="4">Other</option>
                    </select>
                    <input type="text" name="phones[]" class="form-control" placeholder="Phone Number">
                    <button type="button" class="btn btn-danger" onclick="removePhoneField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#phoneContainer .col-lg-8").insertAdjacentHTML('beforeend', newPhoneRow);
        }

        function removePhoneField(button) {
            button.closest(".phone-row").remove();
        }

        function addEmailField() {
            const newEmailRow = `
        <div class="row align-items-center mb-2 email-row">
            <div class="col-md-12">
                <div class="input-group">
                    <div class="input-group-text">
                        <i class="feather-mail"></i>
                    </div>
                    <select class="form-control w-auto" name="email_types[]">
                        <option value="1">Personal</option>
                        <option value="2">Work</option>
                        <option value="3">Other</option>
                    </select>
                    <input type="email" name="emails[]" class="form-control" placeholder="Email Address">
                    <button type="button" class="btn btn-danger" onclick="removeEmailField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#emailContainer .col-lg-8").insertAdjacentHTML('beforeend', newEmailRow);
        }

        function removeEmailField(button) {
            button.closest(".email-row").remove();
        }


        function addSocialMediaField() {
            const newSocialMediaRow = `
        <div class="row align-items-center mb-2 social-media-row">
            <div class="col-md-12">
                <div class="input-group">
                    <!-- Default Social Media Icon -->
                    <div class="input-group-text">
                        <i class="feather-facebook" id="icon-facebook"></i>
                    </div>
                    <!-- Social Media Type -->
                    <select class="form-control w-auto" name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                        <option data-id="1" value="facebook">Facebook</option>
                        <option data-id="2" value="twitter">Twitter</option>
                        <option data-id="3" value="linkedin">LinkedIn</option>
                        <option data-id="4" value="instagram">Instagram</option>
                        <option data-id="5" value="other">Other</option>
                    </select>
                    <!-- Social Media Input -->
                    <input type="text" class="form-control" name="social_media_values[]" placeholder="Social Media Handle or URL">
                    <!-- Remove Button -->
                    <button type="button" class="btn btn-danger" onclick="removeSocialMediaField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#socialMediaContainer .col-lg-8").insertAdjacentHTML('beforeend', newSocialMediaRow);
        }

        function removeSocialMediaField(button) {
            button.closest(".social-media-row").remove();
        }

        function changeSocialMediaIcon(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const selectedId = selectedOption.getAttribute('data-id'); // Get the id of the selected social media
            const iconElement = selectElement.closest('.input-group').querySelector('.input-group-text i');

            // Change the icon based on the selected id
            switch (selectedId) {
                case "1":
                    iconElement.className = "feather-facebook";
                    break;
                case "2":
                    iconElement.className = "feather-twitter";
                    break;
                case "3":
                    iconElement.className = "feather-linkedin";
                    break;
                case "4":
                    iconElement.className = "feather-instagram";
                    break;
                default:
                    iconElement.className = "feather-globe"; // Default icon for 'other'
                    break;
            }
        }

        document.querySelectorAll('.dropdown-item').forEach(function(item) {
            item.addEventListener('click', function(e) {
                e.preventDefault();

                var rating = this.getAttribute('data-value');
                var ratingText = this.innerHTML.trim();

                document.getElementById('ratingDropdown').innerHTML = ratingText + '';

                document.getElementById('ratingInput').value = rating;

                document.getElementById('ratingDropdown').classList.add('border-primary');
                document.getElementById('ratingDropdown').classList.remove('border-primary');
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            var i = 1;

            // Add a new row
            $("#add_row").click(function() {
                b = i - 1;
                $("#addr" + i)
                    .html($("#addr" + b).html())
                    .find("td:first-child")
                    .html(i + 1);
                $("#tab_logic").append('<tr id="addr' + (i + 1) + '"></tr>');
                i++;
            });

            // Delete the last row
            $("#delete_row").click(function() {
                if (i > 1) {
                    $("#addr" + (i - 1)).html("");
                    i--;
                }
                calc();
            });

            // Recalculate totals whenever an input value changes
            $("#tab_logic tbody").on("keyup change", function() {
                calc();
            });

            // Recalculate individual row total when quantity, price, or discount changes
            $("#tab_logic tbody").on("keyup change", ".qty, .price, .discount, .tax", function() {
                calc();
            });
        });

        // Calculate row total (product of qty, price, and discount)
        function calc() {
            var subtotal = 0;

            $("#tab_logic tbody tr").each(function(i, element) {
                var html = $(this).html();
                if (html != "") {
                    var qty = $(this).find(".qty").val();
                    var price = $(this).find(".price").val();
                    var discount = $(this).find(".discount").val();
                    var tax = $(this).find(".tax").val();

                    // Calculate the discount amount
                    var discountAmount = (price * discount) / 100;
                    // Calculate total for this row (with discount applied)
                    var total = (price - discountAmount) * qty;

                    // Calculate tax for this row (based on individual tax column)
                    var taxAmount = (total * tax) / 100;

                    // Update the row with the calculated total and tax amount
                    $(this).find(".total").val((total + taxAmount).toFixed(2)); // Row total includes tax
                }
            });

            calc_total(); // Recalculate the grand total
        }

        // Calculate total amounts (sub total, tax, grand total)
        function calc_total() {
            var total = 0;
            var total_tax = 0;

            // Sum up all row totals
            $(".total").each(function() {
                total += parseFloat($(this).val()) || 0;
            });

            // Calculate Sub Total
            $("#sub_total").val(total.toFixed(2));

            // Calculate Grand Total
            $("#total_amount").val(total.toFixed(2));
        }
    </script>

@endsection
