@extends('layouts.admin-simple')

@section('title', 'Material Site Transfers')

@section('meta')
<meta name="csrf-token" content="{{ csrf_token() }}">
@endsection

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Outgoing</li>
    <li class="breadcrumb-item active">Material Site Transfers</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">Material Site Transfers</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage material transfers between project sites</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            @can('warehouse.outgoing.create')
            <a href="{{ route('warehouse.site-transfers.create') }}" class="btn btn-sm btn-primary" title="Create new site transfer">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                Create New Site Transfer
            </a>
            @endcan
        </div>
    </div>
@endsection

@section('content')

    <!-- Statistics Cards -->
    <div class="row mb-4 warehouse-stats-row">
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Transfers"
                :value="$stats['total_transfers']"
                icon="swap_horiz"
                color="primary"
                subtitle="All site transfers"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="This Month"
                :value="$stats['this_month']"
                icon="today"
                color="info"
                subtitle="Current month transfers"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Completed"
                :value="$stats['completed']"
                icon="check_circle"
                color="success"
                subtitle="Successfully completed"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Value"
                :value="$stats['total_value']"
                icon="attach_money"
                color="warning"
                subtitle="Total transfer value"
                currency="true"
            />
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="card mb-4">
        <div class="card-body py-3">
            <div class="row align-items-end">
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label for="filter_status" class="form-label">Status</label>
                        <select name="filter_status" id="filter_status" class="form-control form-control-sm select2-filter">
                            <option value="">All Status</option>
                            <option value="pending">Pending</option>
                            <option value="completed">Completed</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label for="filter_date_from" class="form-label">Date From</label>
                        <input type="date" id="filter_date_from" class="form-control form-control-sm">
                    </div>
                </div>
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label for="filter_date_to" class="form-label">Date To</label>
                        <input type="date" id="filter_date_to" class="form-control form-control-sm">
                    </div>
                </div>
                <div class="col-md-3">
                    <div style="font-size: 12px; margin-bottom: 8px;">
                        <label class="form-label" style="visibility: hidden;">Actions</label>
                        <div class="d-flex flex-nowrap">
                            <button onclick="applyFilters()" class="btn btn-primary btn-sm mr-2 flex-shrink-0">
                                <i class="material-icons mr-1" style="font-size: 16px;">search</i>
                                Apply Filters
                            </button>
                            <button onclick="clearFilters()" class="btn btn-outline-secondary btn-sm flex-shrink-0">
                                <i class="material-icons mr-1" style="font-size: 16px;">clear</i>
                                Clear
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Site Transfers 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">swap_horiz</i>
                Site Transfers
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <!-- Loading Overlay -->
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay">
                    <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 site transfer data...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    <table id="siteTransfersTable" class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width: 120px;">Transfer #</th>
                                <th style="min-width: 100px;">Date</th>
                                <th style="min-width: 150px;">From Project</th>
                                <th style="min-width: 150px;">To Project</th>
                                <th style="min-width: 80px;">Items</th>
                                <th style="min-width: 100px;">Total Value</th>
                                <th style="min-width: 120px;">Transferred By</th>
                                <th style="min-width: 100px;">Status</th>
                                <th style="min-width: 120px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Data will be loaded via AJAX -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- View Details Modal -->
    <div class="modal fade" id="viewDetailsModal" tabindex="-1" role="dialog" aria-labelledby="viewDetailsModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewDetailsModalLabel">
                        <i class="material-icons align-middle mr-1">swap_horiz</i>
                        Site Transfer 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">
                    <div id="transferDetailsContent">
                        <!-- Content will be loaded dynamically -->
                        <div class="text-center py-4">
                            <i class="material-icons text-muted" style="font-size: 48px;">swap_horiz</i>
                            <div class="text-muted">Loading transfer details...</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</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 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
@endpush

@push('scripts')
    <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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
let siteTransfersTable;

$(document).ready(function() {
    // Initialize Select2 for filter dropdowns
    $('.select2-filter').select2({
        placeholder: function() {
            return $(this).find('option:first').text();
        },
        allowClear: true,
        width: '100%',
        dropdownAutoWidth: false
    });

    initializeDataTable();
});

function initializeDataTable() {
    siteTransfersTable = $('#siteTransfersTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("warehouse.site-transfers.index") }}',
            data: function(d) {
                d.status = $('#filter_status').val();
                d.date_from = $('#filter_date_from').val();
                d.date_to = $('#filter_date_to').val();
            }
        },
        columns: [
            {
                data: 'transfer_number',
                name: 'transfer_number',
                render: function(data) {
                    return `<strong>${data}</strong>`;
                }
            },
            {
                data: 'transfer_date',
                name: 'transfer_date'
            },
            {
                data: 'from_project',
                name: 'from_project',
                render: function(data) {
                    return data || '<span class="text-muted">N/A</span>';
                }
            },
            {
                data: 'to_project',
                name: 'to_project',
                render: function(data) {
                    return data || '<span class="text-muted">N/A</span>';
                }
            },
            {
                data: 'items_count',
                name: 'items_count',
                render: function(data) {
                    // Check if data already contains HTML (badge)
                    if (typeof data === 'string' && data.includes('badge')) {
                        return data;
                    }
                    return `<span class="badge badge-light">${data} items</span>`;
                }
            },
            {
                data: 'total_value',
                name: 'total_value',
                render: function(data) {
                    return `AED ${parseFloat(data || 0).toFixed(2)}`;
                }
            },
            {
                data: 'transferred_by',
                name: 'transferred_by',
                render: function(data) {
                    return data || '<span class="text-muted">N/A</span>';
                }
            },
            {
                data: 'status',
                name: 'status',
                render: function(data, type, row) {
                    // Check if data already contains HTML (badge)
                    if (typeof data === 'string' && data.includes('badge')) {
                        return data;
                    }

                    let badgeClass = 'badge-secondary';
                    let icon = 'info';

                    switch(data.toLowerCase()) {
                        case 'pending':
                            badgeClass = 'badge-warning';
                            icon = 'pending';
                            break;
                        case 'completed':
                            badgeClass = 'badge-success';
                            icon = 'check_circle';
                            break;
                        case 'cancelled':
                            badgeClass = 'badge-danger';
                            icon = 'cancel';
                            break;
                    }

                    return `<span class="badge ${badgeClass}">
                        <i class="material-icons" style="font-size: 12px;">${icon}</i>
                        ${data}
                    </span>`;
                }
            },
            {
                data: 'actions',
                name: 'actions',
                orderable: false,
                searchable: false,
                render: function(data) {
                    return data;
                }
            }
        ],
        order: [[1, 'desc']],
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        language: {
            processing: '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>',
            emptyTable: 'No site transfers found',
            zeroRecords: 'No matching site transfers found'
        }
    });
}

function applyFilters() {
    siteTransfersTable.draw();
}

function clearFilters() {
    $('#filter_status, #filter_date_from, #filter_date_to, #filter_search').val('');
    siteTransfersTable.draw();
}

function viewTransferDetails(transferId) {
    $('#viewDetailsModal').modal('show');

    $('#transferDetailsContent').html(`
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="sr-only">Loading...</span>
            </div>
            <div class="text-muted mt-2">Loading transfer details...</div>
        </div>
    `);

    $.ajax({
        url: `/warehouse/site-transfers/${transferId}`,
        method: 'GET',
        success: function(response) {
            $('#transferDetailsContent').html(response);
        },
        error: function() {
            $('#transferDetailsContent').html(`
                <div class="alert alert-danger">
                    <i class="material-icons align-middle mr-1">error</i>
                    Error loading transfer details. Please try again.
                </div>
            `);
        }
    });
}

function printSingleTransfer(transferId) {
    // Open print window for individual transfer
    const printUrl = '{{ route("warehouse.site-transfers.print-single", ":id") }}'.replace(':id', transferId);
    window.open(printUrl, '_blank', 'width=1200,height=800');
}
</script>

<style>
        /* Filter buttons styling - smaller size to match form fields */
        .card-body .btn-primary.btn-sm,
        .card-body .btn-outline-secondary.btn-sm {
            height: 32px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0 12px;
            font-size: 13px;
        }

        .card-body .btn-primary.btn-sm .material-icons,
        .card-body .btn-outline-secondary.btn-sm .material-icons {
            font-size: 15px !important;
        }

        /* Form control sizing */
        .form-control-sm {
            font-size: 13px;
        }

        /* Select2 styling for filters */
        .select2-container {
            width: 100% !important;
        }

        .select2-container .select2-selection--single {
            height: 32px !important;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 30px;
            padding-left: 12px;
            font-size: 13px;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 30px;
        }

        .select2-dropdown {
            border-radius: 0.375rem;
            border: 1px solid #ced4da;
            width: auto !important;
            min-width: 250px !important;
            max-width: 500px !important;
        }

        /* DataTables search and entries padding */
        .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;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }

        .table-responsive {
            border-radius: 0.375rem;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 500;
            line-height: 1;
            border-radius: 0.375rem;
        }

        .status-pending {
            color: #856404;
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
        }

        .status-completed {
            color: #155724;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status-cancelled {
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
        }

        /* Modal positioning fixes */
        .modal {
            z-index: 1050 !important;
        }

        .modal-backdrop {
            z-index: 1040 !important;
        }

        .modal-dialog-centered {
            display: flex;
            align-items: center;
            min-height: calc(100% - 1rem);
        }

        .modal-content {
            position: relative;
            width: 100%;
            margin: 1.75rem auto;
        }
</style>
@endpush