@extends('admin.layouts.main')
@section('title'){{ __('translations.invoices-create') }}@endsection
@section('sub-title'){{ __('translations.invoices') }}@endsection
@section('content')
<div class="content d-flex flex-column flex-column-fluid" id="kt_content">
  <div class="post d-flex flex-column-fluid" id="kt_post">
    <div id="kt_content_container" class="container-fluid">
      <div class="row">
        <div class="col-12">
          <div class="card card-docs mb-2 shadow">
            <div class="card-header bg-primary text-white">
              <div class="card-title m-0">
                <h3 class="fw-bolder m-0 text-white">{{ __('translations.invoices-create') }}</h3>
              </div>
            </div>
            <div class="card-body">
              <form action="{{route('admin.invoices.store')}}" method="post" enctype="multipart/form-data" id="invoice-form">
                @csrf
                <!-- Invoice Document -->
                <div class="invoice-container bg-white p-5 border rounded shadow-sm mb-5">
                  <!-- Invoice Header Section with Logo and Company Info -->
                  <div class="row mb-5">
                    <div class="col-md-6">
                      <div class="d-flex align-items-center mb-4">
                        @if(isset($setting) && isset($setting->logo))
                          <img src="{{ asset($setting->logo) }}" alt="Company Logo" class="img-fluid me-3" style="max-height: 80px;">
                        @else
                          <img src="{{ asset('logo.png') }}" alt="Company Logo" class="img-fluid me-3" style="max-height: 80px;">
                        @endif
                        <div>
                          @if(isset($setting) && isset($setting->translate(app()->getLocale())->name))
                            <h3 class="fw-bold mb-1">{{ $setting->translate(app()->getLocale())->name }}</h3>
                          @endif
                          @if(isset($setting) && isset($setting->translate(app()->getLocale())->address))
                            <p class="text-muted mb-0"><i class="fas fa-map-marker-alt me-1"></i> {{ $setting->translate(app()->getLocale())->address }}</p>
                          @endif
                          @if(isset($setting) && isset($setting->phone1))
                            <p class="text-muted mb-0"><i class="fas fa-phone me-1"></i> {{ $setting->phone1 }}</p>
                          @endif
                          @if(isset($setting) && isset($setting->email))
                            <p class="text-muted mb-0"><i class="fas fa-envelope me-1"></i> {{ $setting->email }}</p>
                          @endif
                        </div>
                      </div>
                    </div>
                    <div class="col-md-6 text-md-end">
                      <h1 class="display-4 fw-bold text-primary mb-0">{{ __('translations.invoice') }}</h1>
                      <div class="badge bg-primary text-white fs-6 mt-2">#{{ $defaultInvoiceNumber }}</div>
                    </div>
                  </div>

                  <!-- Invoice Info Section -->
                  <div class="row mb-5">
                    <div class="col-md-12 mb-4">
                      <h4 class="fw-bold text-primary border-bottom pb-2">{{ __('translations.invoice-header') }}</h4>
                    </div>

                    <div class="col-md-7">
                      <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                          <label class="form-label fw-bold">{{__('translations.invoices-customer')}} <span class="text-danger">*</span></label>
                          <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#createCustomerModal">
                            <i class="fa fa-plus"></i> {{ __('translations.add-customer') }}
                          </button>
                        </div>
                        <select class="form-select form-select-solid customer-select" name="client_id" required>
                          <option value="">{{ __('translations.select-customer') }}</option>
                          @foreach($clients ?? [] as $client)
                            <option value="{{ $client->id }}">{{ $client->id }} - {{ $client->first_name }} {{ $client->last_name }} @if($client->company_name) ({{ $client->company_name }}) @endif</option>
                          @endforeach
                        </select>
                        @error('client_id')<div class="fv-plugins-message-container invalid-feedback"><strong>{{$message}}</strong></div>@enderror
                      </div>

                      <div class="mb-3">
                        <label class="form-label fw-bold">{{__('translations.invoices-payment-method')}} <span class="text-danger">*</span></label>
                        <select class="form-select form-select-solid" name="payment_method_code" required>
                            @foreach($paymentMethods as $code => $method)
                                <option value="{{ $code }}">{{ $method }}</option>
                            @endforeach
                            <option value="011">{{ __('translations.Credit Card') }}</option>
                        </select>
                      </div>
                    </div>

                    <div class="col-md-5">
                      <div class="bg-light p-4 rounded">
                        <div class="mb-3">
                          <label class="form-label fw-bold">{{__('translations.invoices-number')}}</label>
                          <input type="text" class="form-control form-control-solid" name="number" value="{{ $defaultInvoiceNumber }}" readonly/>
                        </div>
                        <div class="mb-0">
                          <label class="form-label fw-bold">{{__('translations.invoices-date')}}</label>
                          <input type="date" class="form-control form-control-solid " style="text-align: right !important;" name="issue_date" value="{{ $defaultDate }}" readonly/>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Invoice Items Section -->
                  <div class="row mb-5">
                    <div class="col-md-12 mb-4">
                      <h4 class="fw-bold text-primary border-bottom pb-2">{{ __('translations.invoice-items') }}</h4>
                    </div>
                    <div class="col-md-12">
                      <div class="table-responsive">
                        <table class="table table-rounded table-striped border gy-7 gs-7" id="items-table">
                          <thead>
                            <tr class="fw-bold fs-6 text-gray-800 border-bottom bg-light">
                              <th width="40%">{{ __('translations.product') }}</th>
                              <th width="15%">{{ __('translations.price') }}</th>
                              <th width="15%">{{ __('translations.quantity') }}</th>
                              <th width="15%">{{ __('translations.discount') }}</th>
                              <th width="15%">{{ __('translations.total') }}</th>
                              <th width="5%">{{ __('translations.actions') }}</th>
                            </tr>
                          </thead>
                          <tbody id="product-list">
                            <tr class="product-item">
                              <td>
                                <select class="form-select form-select-solid product-select" name="items[0][product_id]" required>
                                  <option value="">{{ __('translations.select-product') }}</option>
                                  @foreach($products as $product)
                                    <option value="{{ $product->id }}" data-price="{{ $product->price }}">{{ $product->name }}</option>
                                  @endforeach
                                </select>
                                <input type="hidden" name="items[0][name]" class="product-name">
                              </td>
                              <td>
                                <input type="number" step="0.01" class="form-control form-control-solid item-price" name="items[0][price]" placeholder="Price" required/>
                              </td>
                              <td>
                                <input type="number" min="1" class="form-control form-control-solid item-quantity" name="items[0][quantity]" placeholder="Quantity" value="1" required/>
                              </td>
                              <td>
                                <input type="number" step="0.01" min="0" class="form-control form-control-solid item-discount" name="items[0][discount]" placeholder="Discount" value="0"/>
                              </td>
                              <td>
                                <input type="number" step="0.01" class="form-control form-control-solid item-total" name="items[0][total]" placeholder="Total" readonly/>
                              </td>
                              <td>
                                <button type="button" class="btn btn-icon btn-danger btn-sm remove-product">
                                  <i class="fa fa-trash"></i>
                                </button>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                      <button type="button" id="add-product" class="btn btn-primary mt-3">
                        <i class="fa fa-plus"></i> {{ __('translations.add-product') }}
                      </button>
                    </div>
                  </div>

                  <!-- Invoice Totals Section -->
                  <div class="row mb-5">
                    <div class="col-md-12 mb-4">
                      <h4 class="fw-bold text-primary border-bottom pb-2">{{ __('translations.invoice-summary') }}</h4>
                    </div>
                    <div class="col-md-6 offset-md-6">
                      <div class="bg-light p-4 rounded shadow-sm">
                        <div class="d-flex justify-content-between mb-3">
                          <span class="fw-bold">{{ __('translations.subtotal') }}:</span>
                          <div>
                            <span id="subtotal" class="fs-5">0.00</span>
                            <span class="ms-1">{{ __('translations.currency') }}</span>
                          </div>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                          <span class="fw-bold">{{ __('translations.total-discount') }}:</span>
                          <div>
                            <span id="total-discount" class="fs-5">0.00</span>
                            <span class="ms-1">{{ __('translations.currency') }}</span>
                          </div>
                        </div>
                        <div class="d-flex justify-content-between pt-2 border-top mt-2">
                          <span class="fw-bold fs-5">{{ __('translations.total') }}:</span>
                          <div>
                            <span id="final-total" class="fs-4 fw-bold text-primary">0.00</span>
                            <span class="ms-1">{{ __('translations.currency') }}</span>
                          </div>
                          <input type="hidden" name="total_price" id="total-price-input" value="0">
                        </div>
                      </div>
                    </div>
                  </div>


                </div>

                <!-- Form Actions -->
                <div class="d-flex pt-3 justify-content-between align-items-center">
                  <a href="{{route('admin.invoices.index')}}" class="btn btn-secondary">
                    <i class="fa fa-arrow-left me-1" aria-hidden="true"></i> {{__('translations.back')}}
                  </a>
                  <div>

                    <button type="submit" class="btn btn-primary">
                      <i class="fa fa-check me-1" aria-hidden="true"></i> {{__('translations.create')}}
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Create Customer Modal -->
<div class="modal fade" id="createCustomerModal" tabindex="-1" aria-labelledby="createCustomerModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-light">
        <h5 class="modal-title" id="createCustomerModalLabel">{{ __('translations.add-customer') }}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="createCustomerForm" action="{{ route('admin.clients.store') }}" method="POST">
          @csrf
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.first-name') }} <span class="text-danger">*</span></label>
              <input type="text" class="form-control" name="first_name" id="first_name" required>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.last-name') }} <span class="text-danger">*</span></label>
              <input type="text" class="form-control" name="last_name" id="last_name" required>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.phone') }} <span class="text-danger">*</span></label>
              <input type="text" class="form-control" name="phone" id="phone" required>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.country_code') }} <span class="text-danger">*</span></label>
              <select class="form-select country-select" name="country_code" id="country_code" required>
                <option value="" selected disabled>{{ __('translations.SelectCountryCode') }}</option>
                @foreach($countries ?? [] as $country)
                  <option value="{{ $country->phone }}" {{ $country->phone == '+962' ? 'selected' : '' }}>
                    {{ $country->name_ar }} ({{ $country->phone }})
                  </option>
                @endforeach
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.age') }} <span class="text-danger">*</span></label>
              <input type="number" class="form-control" name="age" id="age" required>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.Gender') }} <span class="text-danger">*</span></label>
              <select class="form-select gender-select" name="gender" id="gender" required>
                <option value="">{{ __('translations.Gender') }}</option>
                <option value="man">{{ __('translations.man') }}</option>
                <option value="woman">{{ __('translations.women') }}</option>
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.City') }}</label>
              <select class="form-select city-select" name="city_id" id="city_id">
                <option value="">{{ __('translations.SelectCity') }}</option>
                @foreach($cities ?? [] as $city)
                  <option value="{{ $city->id }}">{{ $city->name }}</option>
                @endforeach
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">{{ __('translations.Region') }}</label>
              <select class="form-select region-select" name="region_id" id="region_id">
                <option value="">{{ __('translations.SelectRegion') }}</option>
              </select>
            </div>
            <div class="col-md-12 mb-3">
              <label class="form-label">{{ __('translations.address') }}</label>
              <textarea class="form-control" name="address" id="address" rows="3"></textarea>
            </div>
          </div>
          <div class="d-none">
            <input type="hidden" name="redirect_ajax" value="1">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('translations.close') }}</button>
        <button type="button" class="btn btn-primary" id="saveCustomer">{{ __('translations.save') }}</button>
      </div>
    </div>
  </div>
</div>

<!-- Hidden iframe for form submission -->
<iframe name="customer_submit_frame" id="customer_submit_frame" style="display:none;"></iframe>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        let rowIndex = 0;
        const productList = document.getElementById('product-list');
        const addProductButton = document.getElementById('add-product');
        const printButton = document.getElementById('print-button');
        const finalTotal = document.getElementById('final-total');
        const subtotalSpan = document.getElementById('subtotal');
        const totalDiscountSpan = document.getElementById('total-discount');
        const totalPriceInput = document.getElementById('total-price-input');
        const saveCustomerBtn = document.getElementById('saveCustomer');

        // Initialize Select2 for customer dropdown
        $('.customer-select').select2({
            placeholder: "{{ __('translations.select-customer') }}",
            allowClear: false,
            width: '100%'
        });

        // Initialize Select2 for product dropdowns
        $('.product-select').each(function() {
            $(this).select2({
                placeholder: "{{ __('translations.select-product') }}",
                allowClear: false,
                width: '100%',
                dropdownParent: $(this).closest('td')
            });
        });

        // Function to update product name when product is selected
        function handleProductSelect(select) {
            const row = $(select).closest('.product-item')[0];
            const selectedOption = $(select).find('option:selected');
            const nameInput = row.querySelector('.product-name');
            const priceInput = row.querySelector('.item-price');
            const productId = selectedOption.val();

            // Check if this product is already in the invoice
            if (productId) {
                const existingRows = Array.from(document.querySelectorAll('.product-select')).filter(s =>
                    s !== select[0] && $(s).val() === productId
                );

                if (existingRows.length > 0) {
                    // Product already exists
                    const existingRow = existingRows[0].closest('.product-item');
                    const quantityInput = existingRow.querySelector('.item-quantity');
                    const currentQuantity = parseInt(quantityInput.value) || 0;

                    // Increase quantity by 1
                    quantityInput.value = currentQuantity + 1;

                    // Trigger update of the total
                    updateRowTotal(existingRow);

                    // Reset the current select to empty
                    $(select).val('').trigger('change');

                    // Show warning message
                    alert('{{ __("translations.product-already-exists") }}');

                    return;
                }

                nameInput.value = selectedOption.text().trim();
                priceInput.value = selectedOption.data('price') || 0;
                updateRowTotal(row);
            } else {
                nameInput.value = '';
                priceInput.value = '';
            }
        }

        // Function to update row total
        function updateRowTotal(row) {
            const price = parseFloat(row.querySelector('.item-price').value) || 0;
            const quantity = parseInt(row.querySelector('.item-quantity').value) || 0;
            const discount = parseFloat(row.querySelector('.item-discount').value) || 0;
            const total = (price * quantity) - discount;

            row.querySelector('.item-total').value = total.toFixed(2);
            updateInvoiceTotal();
        }

        // Function to update invoice totals
        function updateInvoiceTotal() {
            let subtotal = 0;
            let totalDiscount = 0;

            document.querySelectorAll('.product-item').forEach(row => {
                const price = parseFloat(row.querySelector('.item-price').value) || 0;
                const quantity = parseInt(row.querySelector('.item-quantity').value) || 0;
                const discount = parseFloat(row.querySelector('.item-discount').value) || 0;

                subtotal += price * quantity;
                totalDiscount += discount;
            });

            const total = subtotal - totalDiscount;

            subtotalSpan.textContent = subtotal.toFixed(2);
            totalDiscountSpan.textContent = totalDiscount.toFixed(2);
            finalTotal.textContent = total.toFixed(2);
            totalPriceInput.value = total.toFixed(2);
        }

        // Initialize the first row
        document.querySelectorAll('.product-select').forEach(select => {
            $(select).on('change', function() {
                handleProductSelect($(this));
            });
        });

        document.querySelectorAll('.item-price, .item-quantity, .item-discount').forEach(input => {
            input.addEventListener('input', function() {
                updateRowTotal(this.closest('.product-item'));
            });
        });

        // Add product button click handler
        addProductButton.addEventListener('click', function() {
            rowIndex++;
            const row = document.createElement('tr');
            row.classList.add('product-item');
            row.innerHTML = `
                <td>
                  <select class="form-select form-select-solid product-select" name="items[${rowIndex}][product_id]" required>
                    <option value="">{{ __('translations.select-product') }}</option>
                    @foreach($products as $product)
                      <option value="{{ $product->id }}" data-price="{{ $product->price }}">{{ $product->name }}</option>
                    @endforeach
                  </select>
                  <input type="hidden" name="items[${rowIndex}][name]" class="product-name">
                </td>
                <td>
                  <input type="number" step="0.01" class="form-control form-control-solid item-price" name="items[${rowIndex}][price]" placeholder="Price" required/>
                </td>
                <td>
                  <input type="number" min="1" class="form-control form-control-solid item-quantity" name="items[${rowIndex}][quantity]" placeholder="Quantity" value="1" required/>
                </td>
                <td>
                  <input type="number" step="0.01" min="0" class="form-control form-control-solid item-discount" name="items[${rowIndex}][discount]" placeholder="Discount" value="0"/>
                </td>
                <td>
                  <input type="number" step="0.01" class="form-control form-control-solid item-total" name="items[${rowIndex}][total]" placeholder="Total" readonly/>
                </td>
                <td>
                  <button type="button" class="btn btn-icon btn-danger btn-sm remove-product">
                    <i class="fa fa-trash"></i>
                  </button>
                </td>
            `;
            productList.appendChild(row);

            // Initialize Select2 for the new product dropdown
            $(row).find('.product-select').select2({
                placeholder: "{{ __('translations.select-product') }}",
                allowClear: false,
                width: '100%',
                dropdownParent: $(row).find('td').first()
            });

            // Add event listeners to the new row
            const newSelect = row.querySelector('.product-select');
            $(newSelect).on('change', function() {
                handleProductSelect($(this));
            });

            row.querySelectorAll('.item-price, .item-quantity, .item-discount').forEach(input => {
                input.addEventListener('input', function() {
                    updateRowTotal(row);
                });
            });
        });

        // Remove product button click handler (using event delegation)
        productList.addEventListener('click', function(event) {
            if (event.target.classList.contains('remove-product') ||
                event.target.parentElement.classList.contains('remove-product')) {
                const button = event.target.classList.contains('remove-product') ?
                               event.target : event.target.parentElement;
                const row = button.closest('.product-item');

                // Only remove if there's more than one row
                if (document.querySelectorAll('.product-item').length > 1) {
                    row.remove();
                    updateInvoiceTotal();
                }
            }
        });

        // Print button click handler
        if (printButton) {
            printButton.addEventListener('click', function() {
                window.print();
            });
        }

        // Save Customer button click handler
        if (saveCustomerBtn) {
            // Initialize Select2 for modal dropdowns
            $('.country-select, .gender-select, .city-select, .region-select').select2({
                dropdownParent: $('#createCustomerModal'),
                width: '100%'
            });

            saveCustomerBtn.addEventListener('click', function() {
                const form = document.getElementById('createCustomerForm');
                if (form.checkValidity()) {
                    // Show loading spinner
                    $(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> {{ __("translations.saving") }}');
                    $(this).prop('disabled', true);

                    // Set the form to submit to our hidden iframe
                    form.target = "customer_submit_frame";
                    form.submit();

                    // Set timeout to check for new client
                    setTimeout(checkForNewClient, 1500);
                } else {
                    form.reportValidity();
                }
            });

            // Function to refresh clients list and add new client if found
            function checkForNewClient() {
                const firstName = $('#first_name').val();
                const lastName = $('#last_name').val();

                // Fetch latest clients
                $.ajax({
                    url: '{{ route("admin.clients.index") }}',
                    type: 'GET',
                    dataType: 'html',
                    success: function(data) {
                        // Find the latest client by parsing the HTML response
                        // This is a workaround since we don't have a direct API endpoint

                        // Create a temp container with the response HTML
                        const tempDiv = document.createElement('div');
                        tempDiv.innerHTML = data;

                        // Re-enable the save button
                        $('#saveCustomer').html('{{ __("translations.save") }}');
                        $('#saveCustomer').prop('disabled', false);

                        // Get all clients from the clients page
                        const clientRows = $(tempDiv).find('table tbody tr');
                        let newClient = null;

                        // Find the client that matches our form data (likely the first row)
                        if (clientRows.length > 0) {
                            const firstClient = clientRows.first();
                            const clientId = firstClient.find('td:first').text().trim();
                            const clientName = firstClient.find('td:eq(1)').text().trim();

                            if (clientName.includes(firstName) && clientName.includes(lastName)) {
                                newClient = {
                                    id: clientId,
                                    first_name: firstName,
                                    last_name: lastName
                                };
                            }
                        }

                        if (newClient) {
                            // Add the new client to the select dropdown
                            const clientSelect = $('.customer-select');
                            const option = new Option(`${newClient.id} - ${newClient.first_name} ${newClient.last_name}`, newClient.id, true, true);
                            clientSelect.append(option).trigger('change');

                            // Close the modal
                            const modal = document.getElementById('createCustomerModal');
                            const bsModal = bootstrap.Modal.getInstance(modal);
                            bsModal.hide();

                            // Clear form
                            form.reset();
                            $('.country-select, .gender-select, .city-select, .region-select').val('').trigger('change');
                        } else {
                            // Close the modal anyway
                            const modal = document.getElementById('createCustomerModal');
                            const bsModal = bootstrap.Modal.getInstance(modal);
                            bsModal.hide();

                            // Refresh the page to show the updated clients list
                            window.location.reload();
                        }
                    },
                    error: function() {
                        // Re-enable the save button
                        $('#saveCustomer').html('{{ __("translations.save") }}');
                        $('#saveCustomer').prop('disabled', false);
                        alert('{{ __("translations.error-creating-customer") }}');
                    }
                });
            }

            // Load regions when city is selected
            $('#city_id').on('change', function() {
                const cityId = $(this).val();
                const regionSelect = $('#region_id');

                // Clear current options
                regionSelect.empty().append('<option value="">{{ __("translations.SelectRegion") }}</option>');

                if (cityId) {
                    // Fetch regions for the selected city
                    fetch(`{{ url("admin/cities") }}/${cityId}/regions`)
                        .then(response => response.json())
                        .then(data => {
                            if (data && data.length > 0) {
                                data.forEach(region => {
                                    const option = new Option(region.name, region.id);
                                    regionSelect.append(option);
                                });
                                regionSelect.trigger('change');
                            }
                        })
                        .catch(error => console.error('Error loading regions:', error));
                }
            });
        }
    });
</script>
@endsection
