@include('layouts.header')

@php
App::setLocale(Auth::user()->lang);
@endphp

<!-- BEGIN: Content-->
<div class="app-content content ">
    <div class="content-overlay"></div>
    <div class="header-navbar-shadow"></div>
    <div class="content-wrapper">
        <!-- header info start -->
        <div class="row">
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $totalInvoices }}</h3>
                            <span>{{ __('Total Invoices') }}</span>
                        </div>
                        <div class="avatar bg-light-primary p-50">
                            <span class="avatar-content">
                                <i data-feather="file-text" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $paidInvoices }}</h3>
                            <span>{{ __('Paid') }}</span>
                        </div>
                        <div class="avatar bg-light-success p-50">
                            <span class="avatar-content">
                                <i data-feather="check-circle" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $unpaidInvoices }}</h3>
                            <span>{{ __('Unpaid') }}</span>
                        </div>
                        <div class="avatar bg-light-warning p-50">
                            <span class="avatar-content">
                                <i data-feather="alert-circle" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-sm-6">
                <div class="card">
                    <div class="card-body d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="fw-bolder mb-75">{{ $totalAmount }}</h3>
                            <span>{{ __('Total Revenue') }}</span>
                        </div>
                        <div class="avatar bg-light-info p-50">
                            <span class="avatar-content">
                                <i data-feather="dollar-sign" class="font-medium-4"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- header info end -->
        <div class="content-body">
            <section class="app-invoice-list">
                <!-- list and filter start -->
                <div class="card">
                    <h5 class="card-header">
                        <div class="input-group input-group-sm position-relative mx-auto">
                            {{ __('Invoice list') }}<span class="badge badge-light-secondary ms-2">{{ $invoices->total() }}</span>
                            <input type="search" class="form-control" id="search" value="{{!empty($_GET['search']) ? $_GET['search'] : ''}}" placeholder="{{__('Search')}}..." />
                            <button type="button" class="btn btn-sm btn-info" id="searchbtn"><i data-feather="search" class="me-0"></i></button>
                            
                            <!-- Filter Dropdown -->
                            <div class="dropdown ms-2">
                                <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="filterDropdown" data-bs-toggle="dropdown">
                                    <i data-feather="filter" class="me-1"></i>{{ __('Filter') }}
                                </button>
                                <div class="dropdown-menu" aria-labelledby="filterDropdown">
                                    <a class="dropdown-item" href="{{ route('invoice.list') }}">{{ __('All') }}</a>
                                    <a class="dropdown-item" href="{{ route('invoice.list', ['status' => 'paid']) }}">{{ __('Paid') }}</a>
                                    <a class="dropdown-item" href="{{ route('invoice.list', ['status' => 'unpaid']) }}">{{ __('Unpaid') }}</a>
                                    <a class="dropdown-item" href="{{ route('invoice.list', ['status' => 'overdue']) }}">{{ __('Overdue') }}</a>
                                </div>
                            </div>
                            
                            <button type="button" class="btn btn-sm btn-primary ms-2" data-bs-toggle="modal" data-bs-target="#addNew">
                                <i data-feather="plus" class="me-1"></i>{{ strtoupper(__('Add new')) }}
                            </button>
                        </div>
                    </h5>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="tbl-bootstr" class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>{{ __('Invoice #') }}</th>
                                        <th>{{ __('Customer') }}</th>
                                        <th>{{ __('Amount') }}</th>
                                        <th>{{ __('Status') }}</th>
                                        <th>{{ __('Due Date') }}</th>
                                        <th>{{ __('Created') }}</th>
                                        <th>{{ __('Actions') }}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($invoices as $invoice)
                                    <tr>
                                        <td><strong>#{{ $invoice->invoice_number }}</strong></td>
                                        <td>{{ $invoice->customer_name }}<br><small class="text-muted">{{ $invoice->customer_email }}</small></td>
                                        <td><strong>{{ \App\Helpers\Helpers::setting('currencyCode') }} {{ number_format($invoice->total_amount, 2) }}</strong></td>
                                        <td>
                                            @if($invoice->status == 'paid')
                                                <span class="badge badge-light-success">{{ __('Paid') }}</span>
                                            @elseif($invoice->status == 'unpaid' && $invoice->due_date < now())
                                                <span class="badge badge-light-danger">{{ __('Overdue') }}</span>
                                            @else
                                                <span class="badge badge-light-warning">{{ __('Unpaid') }}</span>
                                            @endif
                                        </td>
                                        <td>{{ $invoice->due_date->format('M d, Y') }}</td>
                                        <td>{{ $invoice->created_at->format('M d, Y') }}</td>
                                        <td>
                                            <div class="dropdown">
                                                <button type="button" class="btn btn-sm btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                                                    <i data-feather="more-vertical"></i>
                                                </button>
                                                <div class="dropdown-menu">
                                                    <a class="dropdown-item" href="{{ route('invoice.show', $invoice->id) }}">
                                                        <i data-feather="eye" class="me-50"></i>{{ __('View') }}
                                                    </a>
                                                    <a class="dropdown-item" href="{{ route('invoice.pdf', $invoice->id) }}" target="_blank">
                                                        <i data-feather="download" class="me-50"></i>{{ __('Download PDF') }}
                                                    </a>
                                                    @if($invoice->status != 'paid')
                                                    <a class="dropdown-item" href="#" onclick="markAsPaid({{ $invoice->id }})">
                                                        <i data-feather="check" class="me-50"></i>{{ __('Mark as Paid') }}
                                                    </a>
                                                    @endif
                                                    <a class="dropdown-item" href="#" onclick="editInvoice({{ $invoice->id }})">
                                                        <i data-feather="edit" class="me-50"></i>{{ __('Edit') }}
                                                    </a>
                                                    <a class="dropdown-item text-danger" href="#" onclick="deleteInvoice({{ $invoice->id }})">
                                                        <i data-feather="trash" class="me-50"></i>{{ __('Delete') }}
                                                    </a>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        <!-- Pagination -->
                        <div class="d-flex justify-content-center mt-3">
                            {{ $invoices->links() }}
                        </div>
                    </div>
                </div>
                <!-- list and filter end -->
            </section>
        </div>
    </div>
</div>
<!-- END: Content-->

<!-- Modal Add New Invoice -->
<div class="modal fade" id="addNew" tabindex="-1" aria-labelledby="addNewLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addNewLabel">{{ __('Create New Invoice') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="{{ route('invoice.store') }}">
                @csrf
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{{ __('Customer Name') }}*</label>
                            <input type="text" name="customer_name" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{{ __('Customer Email') }}</label>
                            <input type="email" name="customer_email" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{{ __('Customer Phone') }}</label>
                            <input type="text" name="customer_phone" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">{{ __('Due Date') }}*</label>
                            <input type="date" name="due_date" class="form-control" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{{ __('Customer Address') }}</label>
                        <textarea name="customer_address" class="form-control" rows="2"></textarea>
                    </div>
                    
                    <hr>
                    <h6>{{ __('Invoice Items') }}</h6>
                    <div id="invoice-items">
                        <div class="row invoice-item mb-2">
                            <div class="col-md-5">
                                <input type="text" name="items[0][description]" class="form-control" placeholder="{{ __('Description') }}" required>
                            </div>
                            <div class="col-md-2">
                                <input type="number" name="items[0][quantity]" class="form-control item-quantity" placeholder="{{ __('Qty') }}" value="1" min="1" required>
                            </div>
                            <div class="col-md-2">
                                <input type="number" name="items[0][unit_price]" class="form-control item-price" placeholder="{{ __('Price') }}" step="0.01" required>
                            </div>
                            <div class="col-md-2">
                                <input type="text" class="form-control item-total" readonly placeholder="{{ __('Total') }}">
                            </div>
                            <div class="col-md-1">
                                <button type="button" class="btn btn-sm btn-danger remove-item" disabled><i data-feather="x"></i></button>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" id="add-item">
                        <i data-feather="plus" class="me-1"></i>{{ __('Add Item') }}
                    </button>
                    
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label class="form-label">{{ __('Notes') }}</label>
                            <textarea name="notes" class="form-control" rows="3"></textarea>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>{{ __('Subtotal') }}:</span>
                                        <span id="subtotal">0.00</span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>{{ __('Tax') }} (<input type="number" name="tax_percentage" id="tax-percentage" value="0" min="0" max="100" step="0.01" style="width:60px" class="form-control form-control-sm d-inline">%):</span>
                                        <span id="tax-amount">0.00</span>
                                    </div>
                                    <hr>
                                    <div class="d-flex justify-content-between">
                                        <strong>{{ __('Total') }}:</strong>
                                        <strong id="total-amount">0.00</strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('Cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('Create Invoice') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

@include('layouts.footer')

<script>
let itemIndex = 1;

// Add new item
document.getElementById('add-item').addEventListener('click', function() {
    const container = document.getElementById('invoice-items');
    const newItem = document.createElement('div');
    newItem.className = 'row invoice-item mb-2';
    newItem.innerHTML = `
        <div class="col-md-5">
            <input type="text" name="items[${itemIndex}][description]" class="form-control" placeholder="{{ __('Description') }}" required>
        </div>
        <div class="col-md-2">
            <input type="number" name="items[${itemIndex}][quantity]" class="form-control item-quantity" placeholder="{{ __('Qty') }}" value="1" min="1" required>
        </div>
        <div class="col-md-2">
            <input type="number" name="items[${itemIndex}][unit_price]" class="form-control item-price" placeholder="{{ __('Price') }}" step="0.01" required>
        </div>
        <div class="col-md-2">
            <input type="text" class="form-control item-total" readonly placeholder="{{ __('Total') }}">
        </div>
        <div class="col-md-1">
            <button type="button" class="btn btn-sm btn-danger remove-item"><i data-feather="x"></i></button>
        </div>
    `;
    container.appendChild(newItem);
    feather.replace();
    itemIndex++;
    updateRemoveButtons();
});

// Remove item
document.addEventListener('click', function(e) {
    if (e.target.closest('.remove-item')) {
        e.target.closest('.invoice-item').remove();
        calculateTotal();
        updateRemoveButtons();
    }
});

// Calculate total on input change
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('item-quantity') || e.target.classList.contains('item-price') || e.target.id === 'tax-percentage') {
        calculateTotal();
    }
});

function calculateTotal() {
    let subtotal = 0;
    document.querySelectorAll('.invoice-item').forEach(function(item) {
        const quantity = parseFloat(item.querySelector('.item-quantity').value) || 0;
        const price = parseFloat(item.querySelector('.item-price').value) || 0;
        const total = quantity * price;
        item.querySelector('.item-total').value = total.toFixed(2);
        subtotal += total;
    });
    
    const taxPercentage = parseFloat(document.getElementById('tax-percentage').value) || 0;
    const taxAmount = (subtotal * taxPercentage) / 100;
    const totalAmount = subtotal + taxAmount;
    
    document.getElementById('subtotal').textContent = subtotal.toFixed(2);
    document.getElementById('tax-amount').textContent = taxAmount.toFixed(2);
    document.getElementById('total-amount').textContent = totalAmount.toFixed(2);
}

function updateRemoveButtons() {
    const items = document.querySelectorAll('.invoice-item');
    items.forEach((item, index) => {
        const removeBtn = item.querySelector('.remove-item');
        removeBtn.disabled = items.length === 1;
    });
}

function markAsPaid(id) {
    if (confirm('{{ __("Mark this invoice as paid?") }}')) {
        fetch(`/invoice-markpaid`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ invoice_id: id })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            }
        });
    }
}

function deleteInvoice(id) {
    if (confirm('{{ __("Delete this invoice? This action cannot be undone.") }}')) {
        window.location.href = `/invoice-destroy?invoice_id=${id}`;
    }
}

// Search functionality
document.getElementById('searchbtn').addEventListener('click', function() {
    const search = document.getElementById('search').value;
    window.location.href = `{{ route('invoice.list') }}?search=${search}`;
});

document.getElementById('search').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        document.getElementById('searchbtn').click();
    }
});
</script>
