@extends('layouts.admin-simple')

@section('title', 'Fixed Assets Catalog')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Fixed Assets</li>
    <li class="breadcrumb-item active">Catalog</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Fixed Assets Catalog</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage fixed assets and their details</p>
        </div>
        @can('warehouse.fixed-assets.create')
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.fixed-assets.catalog.export') }}" class="btn btn-sm btn-success mr-2" title="Export to Excel">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </a>
            <button onclick="showImportModal()" class="btn btn-sm btn-info mr-2" title="Import assets">
                <i class="material-icons mr-1" style="font-size: 16px;">file_upload</i>
                Import
            </button>
            <a href="{{ route('warehouse.fixed-assets.catalog.create') }}" class="btn btn-sm btn-primary" title="Add new fixed asset">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                Add Asset
            </a>
        </div>
        @endcan
    </div>
@endsection

@section('content')
    <!-- Filters Panel -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0">
                <i class="material-icons mr-2">filter_list</i>
                Filters
            </h6>
        </div>
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label class="font-weight-bold text-muted" style="font-size: 12px;">Category</label>
                        <select id="filter-category" class="form-control form-control-sm select2-dropdown">
                            <option value="">All Categories</option>
                            @foreach($categories ?? [] as $category)
                                <option value="{{ $category->id }}">{{ $category->category_name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label class="font-weight-bold text-muted" style="font-size: 12px;">Condition</label>
                        <select id="filter-condition" class="form-control form-control-sm">
                            <option value="">All Conditions</option>
                            <option value="new">New</option>
                            <option value="good">Good</option>
                            <option value="fair">Fair</option>
                            <option value="poor">Poor</option>
                            <option value="damaged">Damaged</option>
                            <option value="non_functional">Non-Functional</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label class="font-weight-bold text-muted" style="font-size: 12px;">Lifecycle Status</label>
                        <select id="filter-lifecycle" class="form-control form-control-sm">
                            <option value="">All Statuses</option>
                            <option value="in_warehouse">In Warehouse</option>
                            <option value="allocated">Allocated</option>
                            <option value="in_use">In Use</option>
                            <option value="under_maintenance">Under Maintenance</option>
                            <option value="returned">Returned</option>
                            <option value="disposed">Disposed</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label class="font-weight-bold text-muted" style="font-size: 12px;">Status</label>
                        <select id="filter-status" class="form-control form-control-sm">
                            <option value="">All</option>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <div class="form-group mb-0 w-100">
                        <div class="d-flex flex-nowrap">
                            <button onclick="applyFilters()" class="btn btn-primary mr-2 flex-shrink-0">
                                <i class="material-icons mr-1" style="font-size: 16px;">search</i>
                                Apply
                            </button>
                            <button onclick="clearFilters()" class="btn btn-outline-secondary flex-shrink-0">
                                <i class="material-icons mr-1" style="font-size: 16px;">clear</i>
                                Clear
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Assets Table -->
    <div class="card">
        <div class="card-header warehouse-report-header">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">business_center</i>
                Fixed Assets List
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay" style="display: none;">
                    <div class="warehouse-loading-content">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <div class="mt-2">Loading fixed assets...</div>
                        </div>
                    </div>
                </div>

                <div class="warehouse-table-wrapper">
                    <table id="fa-table" class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="width: 40px;">#</th>
                                <th style="min-width: 120px;">Asset Code</th>
                                <th style="min-width: 200px;">Name</th>
                                <th style="min-width: 120px;">Category</th>
                                <th style="min-width: 90px;">Condition</th>
                                <th style="min-width: 100px;">Lifecycle</th>
                                <th style="min-width: 120px;">Location</th>
                                <th style="min-width: 120px;">Book Value</th>
                                <th style="min-width: 180px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('modals')
<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">
                    <i class="material-icons mr-2">file_upload</i>
                    Import Fixed Assets
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="card mb-3">
                    <div class="card-body py-3">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">Step 1: Download Template</h6>
                            <a href="{{ route('warehouse.fixed-assets.catalog.template') }}" class="btn btn-sm btn-outline-info">
                                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                                Download Template
                            </a>
                        </div>
                        <small class="text-muted">Download the Excel template with the correct column format.</small>
                    </div>
                </div>
                <hr>
                <form id="importForm" enctype="multipart/form-data">
                    @csrf
                    <div class="form-group">
                        <h6 class="mb-3">Step 2: Upload Your File</h6>
                        <div class="custom-file">
                            <input type="file" name="file" class="custom-file-input" id="importFile" accept=".xlsx,.xls,.csv" required>
                            <label class="custom-file-label" for="importFile">Choose file...</label>
                        </div>
                        <small class="form-text text-muted mt-2">
                            <i class="material-icons" style="font-size: 14px;">info</i>
                            Supported formats: Excel (.xlsx, .xls) or CSV files. Maximum size: 10MB.
                        </small>
                    </div>
                    <div class="progress mb-3" id="uploadProgress" style="display: none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="importResults" style="display: none;">
                        <div class="alert alert-info">
                            <h6><i class="material-icons mr-1">assessment</i> Import Results</h6>
                            <div id="importSummary"></div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" onclick="importAssets()" class="btn btn-primary" id="importBtn">
                    <i class="material-icons mr-1" style="font-size: 16px;">cloud_upload</i>
                    Import Assets
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
    <link rel="stylesheet" href="{{ asset('admin-assets/css/warehouse-reports.css') }}">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap4.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>
        .btn-sm { padding: 6px 12px; font-size: 12px; line-height: 1.5; border-radius: 4px; }
        .btn-sm .material-icons { font-size: 16px !important; }
        .table th { border-top: none; font-weight: 600; color: #495057; background-color: #f8f9fa; }
        .status-badge { padding: 4px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; text-transform: uppercase; }
        .condition-new { background-color: #d4edda; color: #155724; }
        .condition-good { background-color: #cce5ff; color: #004085; }
        .condition-fair { background-color: #fff3cd; color: #856404; }
        .condition-poor { background-color: #f8d7da; color: #721c24; }
        .condition-damaged { background-color: #f5c6cb; color: #721c24; }
        .condition-non_functional { background-color: #e2e3e5; color: #383d41; }
        .lifecycle-in_warehouse { background-color: #d4edda; color: #155724; }
        .lifecycle-allocated { background-color: #cce5ff; color: #004085; }
        .lifecycle-in_use { background-color: #d1ecf1; color: #0c5460; }
        .lifecycle-under_maintenance { background-color: #fff3cd; color: #856404; }
        .lifecycle-returned { background-color: #e2e3e5; color: #383d41; }
        .lifecycle-disposed { background-color: #f8d7da; color: #721c24; }
        .dataTables_wrapper .dataTables_length { padding: 15px 20px; }
        .dataTables_wrapper .dataTables_filter { padding: 15px 20px 15px 0; }
        .dataTables_wrapper .dataTables_filter input { padding: 8px 15px; min-width: 300px; }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="{{ asset('admin-assets/js/warehouse-reports.js') }}"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap4.min.js"></script>

    <script>
        let faTable;

        $(document).ready(function() {
            $('#tableLoadingOverlay').hide();
            initializeDataTable();

            $('#importFile').on('change', function() {
                var fileName = $(this).val().split('\\').pop();
                $(this).next('.custom-file-label').html(fileName || 'Choose file...');
            });
        });

        function initializeDataTable() {
            faTable = $('#fa-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("warehouse.fixed-assets.catalog.index") }}',
                    type: 'GET',
                    data: function(d) {
                        d.category_id = $('#filter-category').val();
                        d.condition = $('#filter-condition').val();
                        d.lifecycle_status = $('#filter-lifecycle').val();
                        d.status = $('#filter-status').val();
                    },
                    complete: function() {
                        $('#tableLoadingOverlay').hide();
                    },
                    error: function(xhr, error, thrown) {
                        console.error('DataTable AJAX error:', error, thrown);
                        $('#tableLoadingOverlay').hide();
                        showAlert('Error loading data. Please refresh the page.', 'error');
                    }
                },
                columns: [
                    {
                        data: null, orderable: false, searchable: false,
                        render: function(data, type, row, meta) {
                            return meta.row + meta.settings._iDisplayStart + 1;
                        }
                    },
                    {
                        data: 'asset_code', name: 'asset_code',
                        render: function(data) { return '<code>' + data + '</code>'; }
                    },
                    {
                        data: 'asset_name', name: 'asset_name',
                        render: function(data, type, row) {
                            var html = '<div class="font-weight-medium">' + data + '</div>';
                            if (row.serial_number) {
                                html += '<small class="text-muted">S/N: ' + row.serial_number + '</small>';
                            }
                            return html;
                        }
                    },
                    {
                        data: 'category_name', name: 'category_name',
                        render: function(data) {
                            return '<span class="badge badge-secondary">' + (data || 'Uncategorized') + '</span>';
                        }
                    },
                    {
                        data: 'condition', name: 'condition',
                        render: function(data) {
                            var label = (data || 'unknown').replace('_', ' ');
                            return '<span class="status-badge condition-' + (data || 'unknown') + '">' + label.charAt(0).toUpperCase() + label.slice(1) + '</span>';
                        }
                    },
                    {
                        data: 'lifecycle_status', name: 'lifecycle_status',
                        render: function(data) {
                            var label = (data || 'unknown').replace(/_/g, ' ');
                            return '<span class="status-badge lifecycle-' + (data || 'unknown') + '">' + label.charAt(0).toUpperCase() + label.slice(1) + '</span>';
                        }
                    },
                    {
                        data: 'current_location', name: 'current_location',
                        render: function(data) { return data || '<span class="text-muted">-</span>'; }
                    },
                    {
                        data: 'current_book_value', name: 'current_book_value',
                        render: function(data) {
                            var val = parseFloat(data) || 0;
                            return 'AED ' + val.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        }
                    },
                    {
                        data: null, name: 'actions', orderable: false, searchable: false,
                        render: function(data, type, row) {
                            var actions = '<div class="d-flex align-items-center" style="white-space: nowrap;">';
                            actions += '<a href="{{ url("warehouse/fixed-assets/catalog") }}/' + row.id + '" class="btn btn-sm btn-info mr-1" title="View">';
                            actions += '<i class="material-icons mr-1" style="font-size: 14px;">visibility</i>View</a>';

                            @can('warehouse.fixed-assets.edit')
                            actions += '<a href="{{ url("warehouse/fixed-assets/catalog") }}/' + row.id + '/edit" class="btn btn-sm btn-warning mr-1" title="Edit">';
                            actions += '<i class="material-icons mr-1" style="font-size: 14px;">edit</i>Edit</a>';
                            @endcan

                            @can('warehouse.fixed-assets.delete')
                            actions += '<button onclick="deleteAsset(' + row.id + ', \'' + (row.asset_name || '').replace(/'/g, "\\'") + '\')" class="btn btn-sm btn-danger" title="Delete">';
                            actions += '<i class="material-icons mr-1" style="font-size: 14px;">delete</i>Delete</button>';
                            @endcan

                            actions += '</div>';
                            return actions;
                        }
                    }
                ],
                order: [[1, 'asc']],
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'All']],
                language: {
                    processing: '<div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div>',
                    emptyTable: 'No fixed assets found.',
                    zeroRecords: 'No matching records found.'
                },
                dom: '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip'
            });
        }

        function applyFilters() {
            if (faTable) faTable.ajax.reload();
        }

        function clearFilters() {
            $('#filter-category').val('').trigger('change');
            $('#filter-condition').val('');
            $('#filter-lifecycle').val('');
            $('#filter-status').val('');
            if (faTable) faTable.ajax.reload();
        }

        function deleteAsset(id, name) {
            Swal.fire({
                title: 'Delete Fixed Asset?',
                html: 'Are you sure you want to delete <strong>' + name + '</strong>?<br><small class="text-muted">This action cannot be undone.</small>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then(function(result) {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '{{ url("warehouse/fixed-assets/catalog") }}/' + id,
                        type: 'DELETE',
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
                        success: function(response) {
                            if (response.success) {
                                showAlert('Fixed asset deleted successfully.', 'success');
                                if (faTable) faTable.ajax.reload(null, false);
                            } else {
                                showAlert(response.message || 'Failed to delete.', 'error');
                            }
                        },
                        error: function(xhr) {
                            var msg = xhr.responseJSON ? xhr.responseJSON.message : 'An error occurred while deleting.';
                            showAlert(msg, 'error');
                        }
                    });
                }
            });
        }

        function showImportModal() {
            $('#importForm')[0].reset();
            $('.custom-file-label').html('Choose file...');
            $('#uploadProgress').hide();
            $('#importResults').hide();
            $('#importModal').modal('show');
        }

        function importAssets() {
            var fileInput = $('#importFile')[0];
            if (!fileInput.files || !fileInput.files.length) {
                showAlert('Please select a file to import.', 'warning');
                return;
            }

            var formData = new FormData($('#importForm')[0]);
            var btn = $('#importBtn');

            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm mr-1"></span> Importing...');
            $('#uploadProgress').show();
            $('#importResults').hide();

            $.ajax({
                url: '{{ route("warehouse.fixed-assets.catalog.import") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable) {
                            var pct = Math.round((e.loaded / e.total) * 100);
                            $('#uploadProgress .progress-bar').css('width', pct + '%').text(pct + '%');
                        }
                    });
                    return xhr;
                },
                success: function(response) {
                    $('#uploadProgress .progress-bar').css('width', '100%').text('100%');
                    $('#importResults').show();
                    var summary = '<p><strong>Imported:</strong> ' + (response.imported || 0) + ' assets</p>';
                    summary += '<p><strong>Skipped:</strong> ' + (response.skipped || 0) + ' assets</p>';
                    if (response.data && response.data.errors && response.data.errors.length > 0) {
                        summary += '<div class="mt-2"><strong>Errors:</strong><ul class="mb-0">';
                        response.data.errors.forEach(function(err) { summary += '<li class="text-danger">' + err + '</li>'; });
                        summary += '</ul></div>';
                    }
                    $('#importSummary').html(summary);
                    if (response.success) {
                        showAlert(response.message || 'Import completed.', 'success');
                        if (faTable) faTable.ajax.reload(null, false);
                    }
                },
                error: function(xhr) {
                    $('#uploadProgress').hide();
                    var msg = xhr.responseJSON ? xhr.responseJSON.message : 'Import failed. Please try again.';
                    showAlert(msg, 'error');
                },
                complete: function() {
                    btn.prop('disabled', false).html('<i class="material-icons mr-1" style="font-size: 16px;">cloud_upload</i> Import Assets');
                }
            });
        }

        function showAlert(message, type) {
            var iconType = type || 'info';
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: iconType,
                    title: iconType === 'success' ? 'Success' : (iconType === 'error' ? 'Error' : 'Notice'),
                    text: message,
                    timer: iconType === 'success' ? 2000 : undefined,
                    showConfirmButton: iconType !== 'success'
                });
            } else {
                alert(message);
            }
        }
    </script>
@endpush
