@extends('layout.app')

@section('title', 'Sales')

@section('content')

<div class="container-fluid">

    <div class="page-title-head d-flex align-items-center">
        <div class="flex-grow-1">
            <h4 class="page-main-title m-0">Sales</h4>
        </div>
        <div class="text-end">
            <ol class="breadcrumb m-0 py-0">
                <li class="breadcrumb-item"><a href="{{ url('/') }}">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="#">Sales</a></li>
                <li class="breadcrumb-item active">Invoices</li>
            </ol>
        </div>
    </div>

    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header border-light justify-content-between">
                    <div class="d-flex gap-2">
                        <div class="app-search">
                            <input id="saleSearch" type="search" class="form-control" placeholder="Search by # / customer…" />
                            <i class="ti ti-search app-search-icon text-muted"></i>
                        </div>
                    </div>

                    <div class="d-flex align-items-center gap-1 flex-wrap">
                        <div>
                            <select id="salePerPage" class="form-select form-control my-1 my-md-0">
                                <option value="10" selected>10</option>
                                <option value="15">15</option>
                                <option value="25">25</option>
                                <option value="50">50</option>
                            </select>
                        </div>

                        <div class="app-search">
                            <select id="saleStatusFilter" class="form-select form-control my-1 my-md-0">
                                <option value="">All Status</option>
                                <option value="draft">Draft</option>
                                <option value="posted">Posted</option>
                                <option value="completed">Completed</option>
                                <option value="refunded">Refunded</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                            <i class="ti ti-circle app-search-icon text-muted"></i>
                        </div>

                        <div class="app-search">
                            <select id="salePaymentFilter" class="form-select form-control my-1 my-md-0">
                                <option value="">All Payments</option>
                                <option value="unpaid">Unpaid</option>
                                <option value="partial">Partial</option>
                                <option value="paid">Paid</option>
                            </select>
                            <i class="ti ti-cash app-search-icon text-muted"></i>
                        </div>

                        @permission('sales.create')
                        <a href="{{ route('sales.create') }}" class="btn btn-primary ms-1">
                            <i class="ti ti-plus fs-sm me-2"></i> New Sale
                        </a>
                        @endpermission
                    </div>
                </div>

                <div class="table-responsive">
                    <table id="salesTable" class="table table-custom table-centered table-hover w-100 mb-0">
                        <thead class="bg-light align-middle bg-opacity-25 thead-sm">
                            <tr class="text-uppercase fs-xxs">
                                <th class="text-center" style="width: 1%;">S.No</th>
                                <th>Sale #</th>
                                <th>Date</th>
                                <th>Customer</th>
                                <th>Location</th>
                                <th>Channel</th>
                                <th class="text-end">Total</th>
                                <th class="text-end">Balance</th>
                                <th>Payment</th>
                                <th>Status</th>
                                <th class="text-center" style="width: 1%;">Actions</th>
                            </tr>
                        </thead>
                    </table>
                </div>

                <div class="card-footer border-0">
                    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                        <div id="salesInfoSlot" class="text-muted small"></div>
                        <div id="salesPaginationSlot"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

@endsection

@push('styles')
<style>
    .app-search { position: relative; }
    .app-search > .app-search-icon { position: absolute; right: 0.75rem; top: 50%; transform: translateY(-50%); pointer-events: none; }
    .app-search > .form-control { padding-right: 2.25rem; min-width: 160px; }
    #salesTable_wrapper .dataTables_length, #salesTable_wrapper .dataTables_filter { display: none !important; }
    #salesInfoSlot .dataTables_info { padding: 0; color: var(--bs-body-color); font-size: 0.875rem; }
    #salesPaginationSlot .pagination { margin-bottom: 0; }
</style>
@endpush

@push('scripts')
<script>
    $(function () {
        const csrfToken = $('meta[name="csrf-token"]').attr('content');

        const dt = $('#salesTable').DataTable({
            processing: true,
            serverSide: true,
            responsive: false,
            order: [[2, 'desc']],
            ajax: {
                url: '{{ route('sales.data') }}',
                type: 'GET',
                data: function (d) {
                    d.status         = $('#saleStatusFilter').val();
                    d.payment_status = $('#salePaymentFilter').val();
                },
            },
            dom: 'rt<"datatables-tail"ip>',
            pageLength: 10,
            columns: [
                { data: 'DT_RowIndex',     name: 'DT_RowIndex',        orderable: false, searchable: false, className: 'text-center' },
                { data: 'sale_number',     name: 'sales.sale_number' },
                { data: 'sale_date',       name: 'sales.sale_date' },
                { data: 'customer_label',  name: 'customer_label', orderable: false },
                { data: 'location_label',  name: 'location_label',  orderable: false, searchable: false },
                { data: 'channel_label',   name: 'channel_label',   orderable: false, searchable: false },
                { data: 'grand_total',     name: 'sales.grand_total', className: 'text-end' },
                { data: 'balance_due',     name: 'sales.balance_due', className: 'text-end' },
                { data: 'payment_badge',   name: 'sales.payment_status', orderable: false, searchable: false },
                { data: 'status_badge',    name: 'sales.status',         orderable: false, searchable: false },
                { data: 'actions',         name: 'actions',              orderable: false, searchable: false, className: 'text-center' },
            ],
            language: {
                info: 'Showing _START_ to _END_ of _TOTAL_ sales',
                infoEmpty: 'No sales found',
                infoFiltered: ' (filtered from _MAX_ total)',
                emptyTable: 'No sales yet.',
                zeroRecords: 'No sales match your search.',
                processing: '<div class="spinner-border spinner-border-sm text-primary"></div>',
                paginate: { previous: '<i class="ti ti-chevron-left"></i>', next: '<i class="ti ti-chevron-right"></i>' },
            },
            initComplete: function () {
                $('#salesInfoSlot').append($('#salesTable_info'));
                $('#salesPaginationSlot').append($('.datatables-tail'));
            },
        });

        let timer;
        $('#saleSearch').on('keyup', function () {
            clearTimeout(timer);
            const v = this.value;
            timer = setTimeout(() => dt.search(v).draw(), 250);
        });
        $('#salePerPage').on('change', function () { dt.page.len(parseInt(this.value, 10)).draw(); });
        $('#saleStatusFilter, #salePaymentFilter').on('change', function () { dt.draw(); });

        $('#salesTable tbody').on('click', '.js-post-sale', function () {
            const url = $(this).data('url');
            if (!confirm('Post this sale? Inventory will be deducted.')) return;
            $.ajax({
                url, type: 'POST',
                headers: { 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                success: function (res) { if (res.ok) dt.ajax.reload(null, false); else alert(res.message); },
                error: function (xhr) { alert((xhr.responseJSON && xhr.responseJSON.message) || 'Failed.'); },
            });
        });

        $('#salesTable tbody').on('click', '.js-delete-sale', function () {
            const url    = $(this).data('url');
            const number = $(this).data('number');
            if (!confirm('Delete sale ' + number + '? (Soft delete.)')) return;
            $.ajax({
                url, type: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                success: function (res) { if (res.ok) dt.ajax.reload(null, false); else alert(res.message); },
                error: function (xhr) { alert((xhr.responseJSON && xhr.responseJSON.message) || 'Failed.'); },
            });
        });
    });
</script>
@endpush
