@extends('layouts.app')

@section('title', 'Asset Management')

@section('panel-actions')
    @if(auth()->user()->canAccess('assets.manage'))
    <a href="{{ route('assets.create') }}" class="btn btn-primary py-1 px-3" style="font-size: 13px;">
        <i class="fas fa-plus me-1"></i> Add Asset
    </a>
    @endif
@endsection

@section('content')
<div class="row">
    <div class="col-12">
        <div class="card card-primary card-outline">
            <div class="card-header">
                <h3 class="card-title font-weight-bold"><i class="fas fa-box mr-2 text-primary"></i>Company Assets</h3>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="overflow-x: auto;">
                    <table class="table table-hover table-bordered table-striped w-100 mb-0 nowrap" id="assetsTable">

                        <thead>
                            <tr>
                                <!-- Hidden columns: Photo, Serial, Category, Status, Assigned To, Warranty -->
                                <th>Asset ID</th>
                                <th>Name</th>
                                <th style="width: 120px;">Actions</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>
</div>

<!-- View Asset Modal -->
<div class="modal fade" id="viewAssetModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-light">
                <h5 class="modal-title font-weight-bold" id="viewAssetModalLabel">Asset Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body p-4">
                <div class="text-center mb-4">
                    <div id="modalAssetPhoto" class="mb-3"></div>
                    <h5 id="modalAssetName" class="fw-bold mb-1"></h5>
                    <span id="modalAssetStatus" class="badge"></span>
                </div>
                
                <div class="row g-3">
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Asset ID</label>
                        <p id="modalAssetId" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Serial Number</label>
                        <p id="modalAssetSerial" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Category</label>
                        <p id="modalAssetCategory" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Assigned To</label>
                        <p id="modalAssetAssigned" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Purchase Date</label>
                        <p id="modalAssetPurchaseDate" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Warranty Expiry</label>
                        <p id="modalWarrantyExpiry" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Vendor</label>
                        <p id="modalVendor" class="fw-bold mb-0"></p>
                    </div>
                    <div class="col-6">
                        <label class="small text-muted text-uppercase fw-bold">Price</label>
                        <p id="modalPrice" class="fw-bold mb-0"></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer bg-light p-2">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(function() {
    let table = $('#assetsTable').DataTable({
        processing: true,
        serverSide: true,
        responsive: false, // We handle visibility manually
        ajax: "{{ route('assets.data') }}",
        columns: [
            {data: 'asset_id', name: 'asset_id'},
            {data: 'name', name: 'name'},
            {data: 'action', name: 'action', orderable: false, searchable: false}
        ],
        order: [[1, 'desc']],
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search assets...",
            paginate: {
                previous: '<i class="fas fa-chevron-left"></i>',
                next: '<i class="fas fa-chevron-right"></i>'
            }
        }
    });

    // View Asset Details
    $('body').on('click', '.view-asset-btn', function() {
        let id = $(this).data('id');
        
        // Reset modal content
        $('#modalAssetPhoto').html('');
        $('#modalAssetName').text('Loading...');
        $('#modalAssetStatus').html('');
        $('.view-data').text('-');
        
        $('#viewAssetModal').modal('show');

        $.get("{{ url('assets') }}/" + id, function(data) {
            // Photo
            if(data.photo) {
                let imgUrl = "{{ asset('storage') }}/" + data.photo;
                $('#modalAssetPhoto').html('<img src="' + imgUrl + '" class="rounded" style="width: 100px; height: 100px; object-fit: cover;">');
            } else {
                $('#modalAssetPhoto').html('<div class="bg-secondary rounded d-flex align-items-center justify-content-center mx-auto" style="width: 100px; height: 100px;"><i class="fas fa-box text-white fa-2x"></i></div>');
            }

            $('#modalAssetName').text(data.name);
            
            // Status Badge
            $('#modalAssetStatus').html('<span class="badge badge-' + statusColor + '">' + data.status + '</span>');

            $('#modalAssetId').text(data.asset_id);
            $('#modalAssetSerial').text(data.serial_number);
            $('#modalAssetCategory').text(data.category || '-');
            $('#modalAssetAssigned').text(data.employee ? data.employee.name : 'Unassigned');
            
            // Format Dates
            let purchaseDate = data.purchase_date ? new Date(data.purchase_date).toLocaleDateString() : '-';
            let warrantyDate = data.warranty_expiry ? new Date(data.warranty_expiry).toLocaleDateString() : '-';
            
            $('#modalAssetPurchaseDate').text(purchaseDate);
            $('#modalWarrantyExpiry').html(warrantyDate + ' <span class="badge badge-secondary">' + data.warranty_status + '</span>');
            $('#modalVendor').text(data.vendor || '-');
            $('#modalPrice').text(data.purchase_price ? '{{ \App\Models\BusinessSetting::getCurrencySymbol() ?? "$" }}' + data.purchase_price : '-');
        });
    });

    $('body').on('click', '.delete-asset', function() {
        let id = $(this).data('id');
        Swal.fire({
            title: 'Delete this asset?',
            text: "This action cannot be undone!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!',
            customClass: {
                confirmButton: 'btn btn-danger',
                cancelButton: 'btn btn-secondary'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "{{ url('assets') }}/" + id,
                    type: 'DELETE',
                    data: { _token: "{{ csrf_token() }}" },
                    success: function() {
                        Swal.fire({
                            icon: 'success',
                            title: 'Deleted!',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 3000
                        });
                        table.draw();
                    }
                });
            }
        });
    });
});
</script>
@endpush
