@extends('layouts.app')
@push('style')
    <style>
        /* Style for the search results dropdown */
        #customer_results {
            position: absolute;
            z-index: 1000;
            /* Ensure it appears above other elements */
            background-color: #fff;
            border: 1px solid #ccc;
            border-top: none;
            max-height: 200px;
            overflow-y: auto;
            width: 100%;
            /* Match the width of the input field */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        /* Style for individual search items */
        .search-item {
            padding: 8px 12px;
            cursor: pointer;
            list-style-type: none;
            /* Remove bullet points */
        }

        .search-item:hover {
            background-color: #f8f9fa;
            /* Highlight on hover */
        }

        /* Hide the dropdown by default */
        #customer_results {
            display: none;
        }
    </style>
@endpush
@section('main')
    {{-- {{ $brands }} --}}
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Product Edit</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('product.index') }}">Products</a></li>
                        <li class="breadcrumb-item active">Edit</li>
                    </ol>
                </div>
            </div>
        </div><!-- /.container-fluid -->
        {{-- =============================================== --}}
        @if (session('success'))
            <div class="alert alert-success">
                {{ session('success') }}
            </div>
        @endif
        @if (session('error'))
            <div class="alert alert-danger">
                {{ session('error') }}
            </div>
        @endif
        {{-- =============================================== --}}
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-6">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">General</h3>

                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip"
                                title="Collapse">
                                <i class="fas fa-minus"></i></button>
                        </div>
                    </div>
                    <form method="POST" action="{{ route('product.update', $product->id) }}">
                        @csrf
                        @method('PUT')
                        <!-- Customer Info -->
                        <div class="card-body">
                            <div class="form-group">
                                <label for="customer_search">Search Customer:</label>
                                <input type="text" class="form-control" id="customer_search"
                                    placeholder="Search by name or mobile..." autocomplete="off" value="{{ $product->Customer ? $product->Customer->name . ' (' . $product->Customer->number . ')' : '' }}">
                                <input type="hidden" id="customer_info" name="customer_info" value="{{ $product->customer_info }}" readonly>
                                <div id="customer_results" class="search-results"></div> <!-- Dropdown for results -->

                                <button type="button" data-toggle="modal" data-target="#modal-add-customer"
                                    class="btn btn-block">
                                    <i class="fas fa-plus"></i> Add New Customer
                                </button>

                            </div>

                            <!-- Mobile Brand -->
                            <div class="form-group">
                                <label for="brand">Mobile Brand:</label>
                                <select id="brandDropdown" class="form-control" name="brand" required>
                                    <option value="">-- Select Brand --</option>
                                    @foreach ($brands ?? [] as $brand)
                                        <option value="{{ $brand->id }}" {{ $product->brand == $brand->id ? 'selected' : '' }}>{{ $brand->name }}</option>
                                    @endforeach

                                </select>
                                <button type="button" class="btn btn-block" data-toggle="modal"
                                    data-target="#modal-add-brand">+</button>
                            </div>

                            <!-- Mobile Model -->
                            <div class="form-group">
                                <label for="model">Mobile Model:</label>
                                <select id="modelDropdown" class="form-control" name="model" required>
                                    <option value="">-- Select Model --</option>
                                    <option value="{{ $product->model }}" selected>{{ $product->model }}</option>
                                    <!-- Models will be populated here dynamically -->
                                </select>
                                <!-- Button to open model modal -->
                                <button type="button" id="openAddModelModal" class="btn btn-block" data-toggle="modal"
                                    data-target="#modal-add-model">+</button>
                            </div>

                            <!-- IMEI/SN Number -->
                            <div class="form-group">
                                <label for="imei_or_sn">IMEI/SN Number:</label>
                                <input type="text" class="form-control" id="imei_or_sn" name="imei_or_sn" value="{{ $product->imei_or_sn }}" required>
                            </div>

                            <!-- Condition -->
                            <div class="form-group">
                                <label for="condition">Condition:</label>
                                <select id="condition" class="form-control" name="condition" required>
                                    <option value="new" {{ $product->condition == 'new' ? 'selected' : '' }}>New</option>
                                    <option value="old" {{ $product->condition == 'old' ? 'selected' : '' }}>Old</option>
                                </select>
                            </div>

                            <!-- Color -->
                            <div class="form-group">
                                <label for="color">Phone Color:</label>
                                <select id="color" class="form-control" name="color" required>
                                    <option value="Black" {{ $product->color == 'Black' ? 'selected' : '' }}>Black</option>
                                    <option value="White" {{ $product->color == 'White' ? 'selected' : '' }}>White</option>
                                    <option value="Silver" {{ $product->color == 'Silver' ? 'selected' : '' }}>Silver</option>
                                    <option value="Gold" {{ $product->color == 'Gold' ? 'selected' : '' }}>Gold</option>
                                    <option value="Rose Gold" {{ $product->color == 'Rose Gold' ? 'selected' : '' }}>Rose Gold</option>
                                    <option value="Blue" {{ $product->color == 'Blue' ? 'selected' : '' }}>Blue</option>
                                    <option value="Green" {{ $product->color == 'Green' ? 'selected' : '' }}>Green</option>
                                    <option value="Purple" {{ $product->color == 'Purple' ? 'selected' : '' }}>Purple</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="gb">Storage (GB):</label>
                                <select id="gb" class="form-control" name="gb" required>
                                    <option value="16" {{ $product->gb == 16 ? 'selected' : '' }}>16 GB</option>
                                    <option value="32" {{ $product->gb == 32 ? 'selected' : '' }}>32 GB</option>
                                    <option value="64" {{ $product->gb == 64 ? 'selected' : '' }}>64 GB</option>
                                    <option value="128" {{ $product->gb == 128 ? 'selected' : '' }}>128 GB</option>
                                    <option value="256" {{ $product->gb == 256 ? 'selected' : '' }}>256 GB</option>
                                    <option value="512" {{ $product->gb == 512 ? 'selected' : '' }}>512 GB</option>
                                    <option value="1024" {{ $product->gb == 1024 ? 'selected' : '' }}>1 TB</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="buy_price">Buy Price:</label>
                                <input type="number" class="form-control" step="0.01" id="buy_price"
                                    name="buy_price" value="{{ $product->buy_price }}" required>
                            </div>

                            <div class="form-group">
                                <label for="stock">Stock Quantity:</label>
                                <input type="number" class="form-control" id="stock" value="{{ $product->stock }}" name="stock"
                                    required>
                            </div>

                            <button type="submit" class="btn btn-block bg-gradient-primary">Update Product</button>

                            <!-- Popup will display here after successful form submission -->
                    </form>
                </div>


            </div>
            <!-- /.card -->
        </div>

    </section>

    {{-- Add Customer --}}
    <div class="modal fade" id="modal-add-customer">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Add New Customer</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        {{-- <span aria-hidden="true">&times;</span> --}}
                    </button>
                </div>
                <form id="customer_form">
                    @csrf <!-- CSRF Token -->
                    <div class="modal-body">
                        <label for="customer_name">Customer Name:</label>
                        <input type="text" id="customer_name" class="form-control" name="customer_name" required>

                        <label for="customer_number">Customer Number:</label>
                        <input type="tel" id="customer_number" class="form-control" name="customer_number" required>

                        <label for="customer_cpr">Customer CPR:</label>
                        <input type="text" id="customer_cpr" class="form-control" name="customer_cpr">

                        <label for="address">Address:</label>
                        <input type="text" id="address" class="form-control" name="address">

                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Customer</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{-- Add Customer --}}

    {{-- Add Brand --}}
    <div class="modal fade" id="modal-add-brand">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Add New Brand</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        {{-- <span aria-hidden="true">&times;</span> --}}
                    </button>
                </div>
                <form method="POST" action="{{ route('brand.store') }}">
                    @csrf <!-- CSRF Token -->
                    <div class="modal-body">
                        <label for="brand_name">Brand Name:</label>
                        <input type="text" id="brand_name" class="form-control" name="brand_name" required>


                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Brand</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{-- Add Brand --}}

    {{-- Add Mobile Model --}}
    <div class="modal fade" id="modal-add-model">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Add New Model</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        {{-- <span aria-hidden="true">&times;</span> --}}
                    </button>
                </div>
                <form method="POST" action="{{ route('mobile-models.store') }}">
                    @csrf <!-- CSRF Token -->
                    <div class="modal-body">
                        <label for="model_name">Model Name:</label>
                        <input type="hidden" id="brand_id" name="brand_id" required>
                        <input type="text" id="model_name" class="form-control" name="model_name" required>


                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Model</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{-- Add Mobile Model --}}
@endsection

@push('script')
    <script>
        $(document).ready(function() {

            // +++++++++++++++++++++++++   ( 5 )    ++++++++++++++++++++++++++++++++++++++++
            $("#close_modal_btn").click(function() {
                $("#print_invoice_modal").hide(); // Hides the modal
            });

            // Also hide modal when clicking outside of it
            $(window).click(function(event) {
                if ($(event.target).is("#print_invoice_modal")) {
                    $("#print_invoice_modal").hide();
                }
            });
            // +++++++++++++++++++++++++   ( 5 )    ++++++++++++++++++++++++++++++++++++++++

            // +++++++++++++++++++++++++   ( 4 )    ++++++++++++++++++++++++++++++++++++++++
            $('#openAddModelModal').click(function() {
                var brandId = $('#brandDropdown').val(); // Get selected brand ID
                $("#brand_id").val(brandId)
                if (!brandId) {
                    $('#modal-add-model button[type="submit"]').hide();
                    alert('Please select a brand first!');
                    return; // Stop the modal from opening if no brand is selected
                }

                $('#modal-add-model button[type="submit"]').show();
                // Open modal if a brand is selected
                // $('#modal-add-model').modal('show');
            });
            // +++++++++++++++++++++++++   ( 4 )    ++++++++++++++++++++++++++++++++++++++++

            // +++++++++++++++++++++++++   ( 3 )    ++++++++++++++++++++++++++++++++++++++++
            $('#brandDropdown').on('change', function() {
                var brandId = $(this).val(); // Get selected brand ID

                if (brandId) {
                    $.ajax({
                        url: "{{ route('get.models', '') }}/" + brandId, // Call Laravel route
                        type: "GET",
                        success: function(response) {
                            console.log("modelDropdown", response);
                            if (response.success) {
                                var modelDropdown = $('#modelDropdown');
                                modelDropdown.empty(); // Clear existing options
                                modelDropdown.append(
                                    '<option value="">-- Select Model --</option>');

                                $.each(response.models, function(key, model) {
                                    modelDropdown.append('<option value="' + model.id +
                                        '">' + model.name + '</option>');
                                });
                            } else {
                                alert('Error: ' + response.message);
                            }
                        },
                        error: function() {
                            alert("Error fetching models.");
                        }
                    });
                } else {
                    $('#modelDropdown').html(
                        '<option value="">-- Select Model --</option>'
                    ); // Reset models if no brand is selected
                }
            });
            // +++++++++++++++++++++++++   ( 3 )    ++++++++++++++++++++++++++++++++++++++++

            // +++++++++++++++++++++++++   ( 4 )    ++++++++++++++++++++++++++++++++++++++++
            $('#customer_form').on('submit', function(e) {
                e.preventDefault(); // Prevent default form submission

                $.ajax({
                    url: "{{ route('customer.store') }}",
                    type: "POST",
                    data: $(this).serialize(),
                    success: function(response, status, xhr) {
                        if (xhr.status === 201) { // HTTP 201 Created
                            $('#customer_form')[0].reset(); // Reset the form
                            $('#modal-add-customer').modal('hide'); // Hide modal
                            alert(response.message);
                        } else {
                            console.log("Unexpected response status: " + xhr.status);
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 422) { // Validation error
                            let errors = xhr.responseJSON.errors;
                            let errorMessages = Object.values(errors).flat().join("\n");
                            alert("Validation Error:\n" + errorMessages);
                        } else if (xhr.status === 500) { // Server error
                            alert("Server Error! Please try again.");
                        } else {
                            alert("An error occurred. Status: " + xhr.status);
                        }
                        console.log(xhr.responseText);
                    }
                });
            });
            // +++++++++++++++++++++++++   ( 4 )    ++++++++++++++++++++++++++++++++++++++++

            // +++++++++++++++++++++++++   ( 1 )    ++++++++++++++++++++++++++++++++++++++++
            $("#customer_search").on("keyup", function() {
                let query = $(this).val().trim();
                if (query.length < 2) {
                    $("#customer_results").html("").hide(); // Hide if query is too short
                    return;
                }

                $.ajax({
                    url: "{{ route('api.customers.search') }}",
                    type: "GET",
                    data: {
                        query: query
                    },
                    success: function(response) {
                        let resultHTML = "";
                        if (response.length > 0) {
                            resultHTML += '<ul class="">';
                            $.each(response, function(index, customer) {
                                resultHTML += `<li class=" search-item" data-id="${customer.id}" data-name="${customer.name}" data-number="${customer.number}">
                            <strong>${customer.name}</strong> - ${customer.number}
                        </li>`;
                            });
                            resultHTML += '</ul>';
                        } else {
                            resultHTML =
                                '<p class="dropdown-item text-muted">No results found</p>';
                        }

                        $("#customer_results").html(resultHTML).show(); // Show results
                    }
                });
            });

            // Handle selection
            $(document).on("click", ".search-item", function() {
                let customerId = $(this).data("id");
                let customerName = $(this).data("name");
                let customerNumber = $(this).data("number");

                $("#customer_search").val(`${customerName} (${customerNumber})`);
                $("#customer_info").val(customerId); // Store customer ID
                $("#customer_results").hide(); // Hide dropdown after selection
            });

            // Hide dropdown on clicking outside
            $(document).on("click", function(e) {
                if (!$(e.target).closest("#customer_search, #customer_results").length) {
                    $("#customer_results").hide();
                }
            });
            // +++++++++++++++++++++++++   ( 1 )    ++++++++++++++++++++++++++++++++++++++++
        });
    </script>
@endpush
