@extends('layouts.app')

@section('content')
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="page-title">{{ __('Create Quotation') }}</h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a
                            href="{{ route('accounting.quotations.index') }}">{{ __('Quotations') }}</a></li>
                    <li class="breadcrumb-item active">{{ __('Create') }}</li>
                </ol>
            </nav>
        </div>
    </div>

    <form action="{{ route('accounting.quotations.store') }}" method="POST" id="quotationForm">
        @csrf
        
        <!-- Top Section: Quotation Details -->
        <div class="card mb-4">
            <div class="card-header bg-dark border-secondary">
                <h5 class="mb-0">{{ __('Quotation Details') }}</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Customer') }}</label>
                        <select name="customer_id" class="form-select" required>
                            <option value="">{{ __('Select Customer') }}</option>
                            @foreach($customers as $customer)
                                <option value="{{ $customer->id }}">{{ $customer->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Date') }}</label>
                        <input type="date" name="date" class="form-control" value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Expiry Date') }}</label>
                        <input type="date" name="expiry_date" class="form-control"
                            value="{{ date('Y-m-d', strtotime('+30 days')) }}">
                    </div>
                    <div class="col-md-3">
                        <div class="row g-2">
                            <div class="col-md-7">
                                <label class="form-label">{{ __('Currency') }}</label>
                                <select name="currency_id" id="currencySelect" class="form-select">
                                    @foreach($currencies as $currency)
                                        <option value="{{ $currency->id }}" data-rate="{{ $currency->exchange_rate }}" 
                                            {{ $currency->is_base ? 'selected' : '' }}>
                                            {{ $currency->code }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-5">
                                <label class="form-label">{{ __('Ex. Rate') }}</label>
                                <input type="number" name="exchange_rate" id="exchangeRateInput" 
                                    class="form-control" step="0.000001" min="0" 
                                    value="{{ $defaultCurrency ? $defaultCurrency->exchange_rate : 1 }}" readonly>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Middle Section: Items -->
        <div class="card mb-4">
            <div class="card-header bg-dark border-secondary">
                <h5 class="mb-0">{{ __('Items') }}</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="itemsTable">
                        <thead>
                            <tr>
                                <th style="width: 40%">{{ __('Description') }}</th>
                                <th style="width: 15%">{{ __('Qty') }}</th>
                                <th style="width: 20%">{{ __('Unit Price') }}</th>
                                <th style="width: 20%">{{ __('Total') }}</th>
                                <th style="width: 5%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="item-row">
                                <td>
                                    <select name="items[0][product_id]" class="form-select product-select" onchange="fillProductData(this)">
                                        <option value="">{{ __('Select Product') }}</option>
                                        @foreach($products as $product)
                                            <option value="{{ $product->id }}" data-name="{{ $product->name }}"
                                                data-price="{{ $product->price }}"
                                                data-price-usd="{{ $product->price_usd ?? 0 }}"
                                                data-description="{{ $product->description }}"
                                                data-unit-id="{{ $product->unit_id }}">
                                                {{ $product->name }} ({{ number_format($product->price, 2) }}
                                                {{ __('EGP') }} / {{ $product->price_usd ? number_format($product->price_usd, 2) . ' USD' : '-' }})
                                            </option>
                                        @endforeach
                                    </select>
                                    <textarea name="items[0][description]" class="form-control mt-1 description-input"
                                        placeholder="{{ __('Description') }}" rows="2"></textarea>
                                </td>
                                <td>
                                    <input type="number" name="items[0][quantity]" class="form-control quantity"
                                        value="1" min="1" step="0.01" required>
                                </td>
                                <td>
                                    <input type="number" name="items[0][unit_price]" class="form-control price"
                                        value="0.00" min="0" step="0.01" required>
                                </td>
                                <td>
                                    <input type="number" class="form-control total" value="0.00" readonly>
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-sm btn-danger remove-row"><i
                                            class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-sm btn-secondary" id="addItem">
                        <i class="fas fa-plus me-1"></i> {{ __('Add Item') }}
                    </button>
                </div>
            </div>
        </div>

        <!-- Bottom Section: Notes & Summary -->
        <div class="row">
            <!-- Left: Notes -->
            <div class="col-12 col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-dark border-secondary">
                        <h5 class="mb-0">{{ __('Notes & Terms') }}</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">{{ __('Notes') }}</label>
                            <textarea name="notes" class="form-control" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">{{ __('Terms & Conditions') }}</label>
                            <textarea name="terms" class="form-control"
                                rows="3">{{ __('Valid for 30 days. 50% deposit required.') }}</textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right: Summary -->
            <div class="col-12 col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-dark border-secondary">
                        <h5 class="mb-0">{{ __('Summary') }}</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span>{{ __('Subtotal:') }}</span>
                            <span id="subtotalDisplay">0.00</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>{{ __('Discount:') }}</span>
                            <div class="input-group input-group-sm w-50">
                                <select name="discount_type" id="discountType" class="form-select">
                                    <option value="fixed">{{ __('Fixed') }}</option>
                                    <option value="percent">{{ __('%') }}</option>
                                </select>
                                <input type="number" name="discount_value" id="discountInput" class="form-control" value="0" min="0" step="0.01">
                            </div>
                        </div>
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>{{ __('Shipping:') }}</span>
                            <input type="number" name="shipping_amount" id="shippingInput" class="form-control form-control-sm w-50 text-end" value="0" min="0" step="0.01">
                        </div>
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>{{ __('Extra Exp:') }}</span>
                            <div class="input-group input-group-sm w-50">
                                <input type="text" name="extra_expenses_note" class="form-control" placeholder="Note">
                                <input type="number" name="extra_expenses_amount" id="extraExpensesInput" class="form-control text-end" value="0" min="0" step="0.01">
                            </div>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between">
                            <span class="fw-bold">{{ __('Grand Total:') }}</span>
                            <span class="fw-bold fs-5" id="grandTotalDisplay">0.00</span>
                        </div>
                        <hr>
                        <button type="submit" class="btn btn-primary w-100 mb-2">
                            <i class="fas fa-save me-2"></i>{{ __('Save Quotation') }}
                        </button>
                        <a href="{{ route('accounting.quotations.index') }}"
                            class="btn btn-outline-light w-100">{{ __('Cancel') }}</a>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            let rowCount = 1;

            function calculateRow(row) {
                const qty = parseFloat(row.find('.quantity').val()) || 0;
                const price = parseFloat(row.find('.price').val()) || 0;
                const total = qty * price;
                row.find('.total').val(total.toFixed(2));
                calculateTotals();
            }

            function calculateTotals() {
                let subtotal = 0;
                $('.item-row').each(function () {
                    subtotal += parseFloat($(this).find('.total').val()) || 0;
                });

                // Discount
                const discountType = document.getElementById('discountType').value;
                let discountValue = parseFloat(document.getElementById('discountInput').value) || 0;
                let discountAmount = 0;

                if (discountType === 'percent') {
                    discountAmount = (subtotal * discountValue) / 100;
                } else {
                    discountAmount = discountValue;
                }

                // Expenses
                const shippingAmount = parseFloat(document.getElementById('shippingInput').value) || 0;
                const extraExpensesAmount = parseFloat(document.getElementById('extraExpensesInput').value) || 0;

                const grandTotal = subtotal - discountAmount + shippingAmount + extraExpensesAmount;

                $('#subtotalDisplay').text(subtotal.toFixed(2));
                $('#grandTotalDisplay').text(grandTotal.toFixed(2));
            }
            
            // Event Listeners for Calculation
            $('#discountInput, #shippingInput, #extraExpensesInput').on('input', calculateTotals);
            $('#discountType').change(calculateTotals);

            $('#addItem').click(function () {
                const newRow = `
                            <tr class="item-row">
                                <td>
                                    <select name="items[${rowCount}][product_id]" class="form-select product-select" onchange="fillProductData(this)">
                                        <option value="">{{ __('Select Product') }}</option>
                                        @foreach($products as $product)
                                            <option value="{{ $product->id }}" data-name="{{ $product->name }}"
                                                data-price="{{ $product->price }}"
                                                data-price-usd="{{ $product->price_usd ?? 0 }}"
                                                data-description="{{ $product->description }}"
                                                data-unit-id="{{ $product->unit_id }}">
                                                {{ $product->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <textarea name="items[${rowCount}][description]" class="form-control mt-1 description-input" placeholder="{{ __('Description') }}" rows="2"></textarea>
                                </td>
                                <td>
                                    <input type="number" name="items[${rowCount}][quantity]" class="form-control quantity" value="1" min="1" step="0.01" required>
                                </td>
                                <td>
                                    <input type="number" name="items[${rowCount}][unit_price]" class="form-control price" value="0.00" min="0" step="0.01" required>
                                </td>
                                <td>
                                    <input type="number" class="form-control total" value="0.00" readonly>
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-sm btn-danger remove-row"><i class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                        `;
                $('#itemsTable tbody').append(newRow);
                rowCount++;
            });

            $(document).on('click', '.remove-row', function () {
                if ($('.item-row').length > 1) {
                    $(this).closest('tr').remove();
                    calculateTotals();
                }
            });

            $(document).on('input', '.quantity, .price', function () {
                calculateRow($(this).closest('tr'));
            });

             // Currency Change
             $('#currencySelect').change(function() {
                const selectedOption = $(this).find('option:selected');
                const rate = selectedOption.data('rate');
                const rateInput = $('#exchangeRateInput');
                rateInput.val(rate);
                
                 if (parseFloat(rate) !== 1.0) {
                     rateInput.prop('readonly', false);
                 } else {
                     // rateInput.prop('readonly', true);
                     // Allow edit always
                     rateInput.prop('readonly', false);
                 }
            });
        });

        function fillProductData(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const row = selectElement.closest('.item-row');

             // Get selected Quote Currency code (simple check)
            const currencySelect = document.getElementById('currencySelect');
            const selectedCurrencyText = currencySelect ? currencySelect.options[currencySelect.selectedIndex].text : 'EGP';
            let useUsd = false;

            if (selectedCurrencyText.includes('USD') || selectedCurrencyText.includes('Dollar')) {
                useUsd = true;
            }

            if (selectedOption.value) {
                const productName = selectedOption.getAttribute('data-name');
                const productPrice = selectedOption.getAttribute('data-price');
                const productPriceUsd = selectedOption.getAttribute('data-price-usd');
                const productDescription = selectedOption.getAttribute('data-description');

                // Fill description
                row.querySelector('.description-input').value = productDescription || productName;
                
                  // Fill price
                let finalPrice = parseFloat(productPrice);
                if (useUsd && parseFloat(productPriceUsd) > 0) {
                    finalPrice = parseFloat(productPriceUsd);
                }
                
                row.querySelector('.price').value = finalPrice.toFixed(2);

                // Trigger calculation
                const priceInput = row.querySelector('.price');
                const event = new Event('input', { bubbles: true });
                priceInput.dispatchEvent(event);
            }
        }
    </script>
@endsection