@extends('layouts.app')

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

@section('content')
    <!-- [ page-header ] start -->
    <form id="createProductForm" method="POST" action="{{ route('products.store') }}" enctype="multipart/form-data">
        @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">Product</h5>
                </div>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('myactivities') }}">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">
                        <button type="submit" name="is_draft" value="1" class="btn btn-light-brand">
                            <i class="feather-layers me-2"></i>
                            <span>Save as Draft</span>
                        </button>
                        <button type="submit" name="is_draft" value="0" class="btn btn-primary">
                            <i class="feather-user-plus me-2"></i>
                            <span>Create Product</span>
                        </button>
                    </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">
            @if($errors->any())<div class="alert alert-danger"><strong>Please correct the product information.</strong><ul class="mb-0">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>@endif
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-top-0">
                        <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">Product Information:</span>
                                        </h5>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Product Images: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="mb-4 mb-md-0 d-flex align-items-center gap-4">
                                                    <div
                                                        class="wd-100 ht-100 position-relative overflow-hidden border border-gray-2 rounded">
                                                        <img id="first-upload-image"
                                                            src="assets/images/emptyImg.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"
                                                            name="images[]" accept="image/*"
                                                            onchange="previewImages(event)" multiple>
                                                    </div>
                                                    <div id="image-previews" class="d-flex gap-4 flex-wrap">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="productNameInput" class="fw-semibold">Product
                                                    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="product_name" id="productNameInput" value="{{ old('product_name') }}"
                                                        placeholder="Product Name">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="productCodeInput" class="fw-semibold">Product
                                                    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="product_code" id="productCodeInput" value="{{ old('product_code') }}"
                                                        placeholder="Product 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">Product Type:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="product_type"
                                                    id="product-type-dropdown">
                                                    <option value="">Select Product Type</option>
                                                    <option value="1" @selected(old('product_type')==1)>Items</option>
                                                    <option value="2" @selected(old('product_type')==2)>Services</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center hide-for-services">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Unit:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="unit"
                                                    id="unit-dropdown">
                                                    <option value="">Select Unit</option>
                                                    @foreach($units as $unit)<option value="{{ $unit->id }}" @selected(old('unit')==$unit->id)>{{ $unit->name }}</option>@endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center hide-for-services">
                                            <div class="col-lg-4 mb-2"><label for="stockQuantity" class="fw-semibold">Stock Quantity:</label></div>
                                            <div class="col-lg-12"><input type="number" class="form-control" name="stock_quantity"
                                                id="stockQuantity" value="{{ old('stock_quantity') }}" min="0" step="0.001"
                                                placeholder="Leave empty for unlimited/non-stock item"></div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="productCategoryDropdown"
                                                    class="fw-semibold">Product
                                                    Category:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="product_category"
                                                    id="productCategoryDropdown">
                                                    <option value="">Select Product Category</option>
                                                    @foreach($categories as $category)<option value="{{ $category->id }}" @selected(old('product_category')==$category->id)>{{ $category->name }}</option>@endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center hide-for-services">
                                            <div class="col-lg-4 mb-2">
                                                <label for="priceInput" class="fw-semibold">Price:</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="price"
                                                        id="priceInput" value="{{ old('price') }}" min="0" step="0.01" placeholder="Price">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center hide-for-services">
                                            <div class="col-lg-4 mb-2">
                                                <label for="taxInput" class="fw-semibold">Tax (%):</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-percent"></i>
                                                    </div>
                                                    <input type="number" class="form-control" name="tax"
                                                        id="taxInput" value="{{ old('tax') }}" min="0" max="100" step="0.01" placeholder="Tax Percentage">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center hide-for-services">
                                            <div class="col-lg-4 mb-2">
                                                <label for="discountInput" class="fw-semibold">Discount
                                                    (%):</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-percent"></i>
                                                    </div>
                                                    <input type="number" class="form-control"
                                                        name="discount" id="discountInput" value="{{ old('discount') }}" min="0" max="100" step="0.01"
                                                        placeholder="Discount Percentage">
                                                </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">{{ old('description') }}</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">Status: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <select class="form-control" name="status"
                                                    data-select2-selector="status">
                                                    <option value="active" data-bg="bg-success" @selected(old('status','active')==='active')>
                                                        Active
                                                    </option>
                                                    <option value="inactive" data-bg="bg-warning" @selected(old('status')==='inactive')>Inactive
                                                    </option>
                                                    <option value="archived" data-bg="bg-danger" @selected(old('status')==='archived')>Archived
                                                    </option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </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>

    <script>
        function previewImages(event) {
            const files = event.target.files;
            const previewContainer = document.getElementById('image-previews');
            const firstImage = document.getElementById('first-upload-image');

            // Reset previous previews
            previewContainer.innerHTML = '';
            firstImage.src = '{{ asset('assets/images/emptyImg.png') }}';

            // Limit to a maximum of 4 files
            if (files.length > 4) {
                alert("You can only select a maximum of 4 images.");
                return;
            }

            // Process and preview selected images
            Array.from(files).slice(0, 4).forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    if (index === 0) {
                        firstImage.src = e.target.result;
                    } else {
                        const imgElement = document.createElement('img');
                        imgElement.src = e.target.result;
                        imgElement.classList.add('upload-pic', 'img-fluid', 'rounded', 'h-25', 'w-25');
                        previewContainer.appendChild(imgElement);
                    }
                };
                reader.readAsDataURL(file);
            });
        }
    </script>


    <script>
        document.getElementById('product-type-dropdown').addEventListener('change', function() {
            const specificFields = document.querySelectorAll('.hide-for-services');
            if (this.value === "2") { // 2 = Services
                specificFields.forEach(field => field.classList.add('d-none'));
            } else {
                specificFields.forEach(field => field.classList.remove('d-none'));
            }
        });
    </script>

@endsection
