@extends('layouts.app')
@section('title', 'Customers')
@push('plugin-styles')
<link rel="stylesheet" href="{{ asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css') }}">
<link rel="stylesheet" href="{{ asset('theme/vendors/flatpickr/flatpickr.min.css') }}">
<link rel="stylesheet" href="{{ asset('theme/vendors/sweetalert2/sweetalert2.min.css') }}">
@endpush
@section('content')
<div class="accordion mb-3" id="customerFilterAccordion">
	<div class="accordion-item">
		<h2 class="accordion-header" id="customerFilterHeading">
			<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#customerFilterCollapse" aria-expanded="false" aria-controls="customerFilterCollapse">
				Filters
			</button>
		</h2>
		<div id="customerFilterCollapse" class="accordion-collapse collapse" aria-labelledby="customerFilterHeading" data-bs-parent="#customerFilterAccordion">
			<div class="accordion-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" id="filterStatus">
                            <option value="">All Status</option>
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                    <div class="col-md-9">
                        <label class="form-label">Search</label>
                        <input type="text" class="form-control" id="filterSearch" placeholder="Search by name, email, phone, or code...">
                    </div>
                </div>
                <div class="mt-3 d-flex gap-2">
                    <button type="button" class="btn btn-primary" id="btnApplyFilters">
                        <i class="fas fa-search me-2"></i>
                        Apply
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="btnResetFilters">
                        <i class="fas fa-times me-2"></i>
                        Clear
                    </button>
                </div>
			</div>
		</div>
	</div>
</div>

<div class="card">
	<div class="card-body">
		<div class="d-flex justify-content-between align-items-center mb-3">
			<h6 class="card-title mb-0">Customers</h6>
            <a href="{{ route('customers.create') }}" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i>
                Add Customer
            </a>
		</div>
		@if(session('success'))<div class="alert alert-success">{{ session('success') }}</div>@endif
		@if($errors->any())<div class="alert alert-danger">{{  print_r($errors->all(), true) }}</div>@endif
		<div class="table-responsive">
			<table id="customers-table" class="table table-hover">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Code</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Tax Number</th>
                        <th>Opening Balance</th>
                        <th>Current Balance</th>
                        <th>Credit Limit</th>
                        <th>Payment Terms</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- DataTables will populate this -->
                </tbody>
            </table>
        </div>
    </div>
</div>
@endsection

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/datatables.net/dataTables.js') }}"></script>
<script src="{{ asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js') }}"></script>

<script>
$(document).ready(function() {
    // Check if DataTable is available
    if (typeof $.fn.DataTable === 'undefined') {
        console.error('DataTable is not loaded');
        alert('DataTable library is not loaded. Please refresh the page.');
        return;
    }

    // Initialize DataTable
    var table = $('#customers-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "{{ route('customers.index') }}",
            data: function(d) {
                d.status = $('#filterStatus').val();
                d.search = $('#filterSearch').val();
            },
            error: function(xhr, error, thrown) {
                console.error('DataTable AJAX Error:', error, thrown);
                console.error('Response:', xhr.responseText);
                alert('Error loading data: ' + error);
            }
        },
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'code', name: 'code' },
            { data: 'email', name: 'email' },
            { data: 'phone', name: 'phone' },
            { data: 'tax_number', name: 'tax_number' },
            { data: 'opening_balance_formatted', name: 'opening_balance' },
            { data: 'balance_formatted', name: 'balance' },
            { data: 'credit_limit_formatted', name: 'credit_limit' },
            { data: 'pay_terms', name: 'pay_terms' },
            { data: 'status_badge', name: 'is_active' },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ],
        order: [[0, 'desc']],
        pageLength: 25,
        responsive: true
    });

    // Apply filters
    $('#btnApplyFilters').click(function() {
        table.draw();
    });

    // Reset filters
    $('#btnResetFilters').click(function() {
        $('#filterStatus').val('');
        $('#filterSearch').val('');
        table.draw();
    });

    // Search on enter key
    $('#filterSearch').keypress(function(e) {
        if (e.which == 13) {
            table.draw();
        }
    });
});

</script>
@endpush
