@extends('layouts.dashboard.superadminapp')

@section('title', 'Tax Invoice List')

@section('styles')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css">
<style>
    #invoiceTable {
        width: 100% !important;
    }
    #invoiceTable th, #invoiceTable td {
        white-space: nowrap;
        font-size: 0.8rem;
        padding: 0.5rem !important;
        vertical-align: middle;
    }
    #invoiceTable td.wrap-text {
        white-space: normal;
        max-width: 150px;
    }
    .table-actions .btn {
        padding: 0.2rem 0.4rem;
        font-size: 0.7rem;
        margin: 0 1px;
    }
    .summary-card {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
    }
    .summary-card .card-body {
        padding: 1rem;
    }
    .summary-icon {
        font-size: 2rem;
        opacity: 0.3;
    }
    .section-card {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
    }
    .section-card .card-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-radius: 0.5rem 0.5rem 0 0 !important;
    }
</style>
@endsection

@section('content')
    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL | Tax Invoice List</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <!-- Alerts -->
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-primary h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Invoices</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $invoices->count() }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-file-invoice summary-icon text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-success h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Amount</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">₹{{ number_format($invoices->sum('total_amount'), 2) }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-rupee-sign summary-icon text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-info h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Tax</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">₹{{ number_format($invoices->sum('total_tax_amount'), 2) }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-percentage summary-icon text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-warning h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">This Month</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $invoices->where('invoice_date', '>=', now()->startOfMonth())->count() }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-alt summary-icon text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Data Table Card -->
    <div class="card section-card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="fas fa-table mr-2"></i>Tax Invoices</span>
            <a href="{{ route('superadmin.invoice.invoiceorder') }}" class="btn btn-light btn-sm" title="Create New Invoice">
                <i class="fa fa-plus-square mr-1"></i> Add New
            </a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="invoiceTable">
                    <thead class="thead-light">
                        <tr class="text-center">
                            <th>#</th>
                            <th>Invoice No</th>
                            <th>Date</th>
                            <th>Company</th>
                            <th>GST No</th>
                            <th>Buyer Order</th>
                            <th>Destination</th>
                            <th>Total Amount</th>
                            <th>Tax Amount</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($invoices as $index => $invoice)
                            <tr id="row-{{ $invoice->id }}" class="text-center">
                                <td>{{ $index + 1 }}</td>
                                <td class="font-weight-bold">{{ $invoice->invoice_no }}</td>
                                <td>{{ \Carbon\Carbon::parse($invoice->invoice_date)->format('d M Y') }}</td>
                                <td class="text-left wrap-text">
                                    <strong>{{ $invoice->company->company ?? '-' }}</strong>
                                    @if($invoice->company->email ?? null)
                                        <br><small class="text-muted">{{ $invoice->company->email }}</small>
                                    @endif
                                </td>
                                <td><small>{{ $invoice->company->gstno ?? '-' }}</small></td>
                                <td>{{ $invoice->buyer_order_no ?? '-' }}</td>
                                <td>{{ $invoice->destination ?? '-' }}</td>
                                <td class="text-right font-weight-bold text-success">₹{{ number_format($invoice->total_amount, 2) }}</td>
                                <td class="text-right">₹{{ number_format($invoice->total_tax_amount, 2) }}</td>
                                <td>
                                    <div class="btn-group table-actions" role="group">
                                        <a href="{{ route('superadmin.invoice.print', $invoice->id) }}" target="_blank" class="btn btn-info btn-sm" title="View/Print">
                                            <i class="fa fa-eye"></i>
                                        </a>
                                        <a href="{{ route('superadmin.invoice.edit', $invoice->id) }}" class="btn btn-warning btn-sm" title="Edit">
                                            <i class="fa fa-edit"></i>
                                        </a>
                                        <button class="btn btn-danger btn-sm delete-btn" data-id="{{ $invoice->id }}" data-invoice="{{ $invoice->invoice_no }}" title="Delete">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white py-2">
                    <h6 class="modal-title mb-0"><i class="fas fa-exclamation-triangle mr-2"></i>Delete Invoice</h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">Are you sure you want to delete this invoice?</p>
                    <p class="mb-0"><strong id="deleteItemName"></strong></p>
                    <small class="text-muted">This action cannot be undone.</small>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger btn-sm" id="confirmDeleteBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Delete</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>
<script>
$(document).ready(function() {
    // Initialize DataTable
    var table = $('#invoiceTable').DataTable({
        dom: '<"row"<"col-sm-12 col-md-6"B><"col-sm-12 col-md-6"f>>rtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-sm btn-secondary' },
            { extend: 'csv', className: 'btn btn-sm btn-secondary' },
            { extend: 'excel', className: 'btn btn-sm btn-secondary' },
            { extend: 'pdf', className: 'btn btn-sm btn-secondary' },
            { extend: 'print', className: 'btn btn-sm btn-secondary' }
        ],
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, 'desc']],
        columnDefs: [
            { orderable: false, targets: [9] }
        ],
        language: {
            emptyTable: "No invoices found"
        }
    });

    // Delete button click
    var deleteId = null;
    $(document).on('click', '.delete-btn', function() {
        deleteId = $(this).data('id');
        $('#deleteItemName').text($(this).data('invoice'));
        $('#deleteModal').modal('show');
    });

    // Confirm delete
    $('#confirmDeleteBtn').on('click', function() {
        if (!deleteId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Deleting...');

        $.ajax({
            url: '{{ url("/superadmin/invoices") }}/' + deleteId,
            type: 'DELETE',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(response) {
                $('#deleteModal').modal('hide');
                table.row('#row-' + deleteId).remove().draw(false);
                showToast('success', response.message || 'Invoice deleted successfully!');
            },
            error: function(xhr) {
                showToast('error', xhr.responseJSON?.message || 'Failed to delete invoice.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Delete');
                deleteId = null;
            }
        });
    });

    // Toast notification helper
    function showToast(type, message) {
        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        var toastHtml = `
            <div class="toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 280px;">
                <div class="toast-body d-flex align-items-center">
                    <i class="fas ${icon} mr-2"></i>
                    <span>${message}</span>
                    <button type="button" class="ml-auto close text-white" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }
});
</script>
@endsection
