@extends('layouts.admin-simple')

@section('title', 'Material Issue')

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

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Inventory</li>
    <li class="breadcrumb-item active">Material Issue</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 Issue</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Track and view materials that have been issued from inventory</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <!-- No action buttons needed for issued materials view -->
        </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 Issued"
                :value="$stats['total_issued'] ?? 25"
                icon="assignment"
                color="primary"
                subtitle="All material issued"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Recently Issued"
                :value="$stats['recently_issued'] ?? 8"
                icon="schedule"
                color="info"
                subtitle="Last 7 days"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Pending Issues"
                :value="$stats['pending_issues'] ?? 12"
                icon="pending"
                color="warning"
                subtitle="Awaiting dispatch"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Value"
                :value="number_format($stats['total_value'] ?? 0, 2)"
                icon="monetization_on"
                color="success"
                subtitle="Value of issued materials"
                :currency="true"
            />
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="warehouse-filter-panel">
        <div class="warehouse-panel-header">
            <h5 class="warehouse-panel-title">
                <i class="material-icons">filter_list</i>
                Filters
            </h5>
        </div>
        <div class="warehouse-panel-body">
            <div class="row">
                <div class="col-xl-3 col-md-6 mb-3">
                    <x-warehouse.select2-dropdown
                        name="filter_status"
                        id="filter_status"
                        label="Status"
                        placeholder="All Status"
                        :options="[
                            ['value' => '', 'text' => 'All Status'],
                            ['value' => 'pending', 'text' => 'Pending'],
                            ['value' => 'successful', 'text' => 'Successful'],
                            ['value' => 'canceled', 'text' => 'Canceled']
                        ]"
                        allowClear="true"
                    />
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <label class="form-label">Date From</label>
                    <input type="date" id="filter_date_from" class="form-control">
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <label class="form-label">Date To</label>
                    <input type="date" id="filter_date_to" class="form-control">
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <x-warehouse.select2-dropdown
                        name="filter_project"
                        id="filter_project"
                        label="Project"
                        placeholder="All Projects"
                        :options="[['value' => '', 'text' => 'All Projects']]"
                        allowClear="true"
                    />
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
                <button type="button" onclick="applyFilters()" class="btn btn-primary" id="apply_filters">
                    <i class="material-icons mr-1" style="font-size: 18px; vertical-align: middle;">filter_list</i>
                    Apply Filters
                </button>

                <button type="button" onclick="clearFilters()" class="btn btn-outline-secondary" id="clear_filters">
                    <i class="material-icons mr-1" style="font-size: 18px; vertical-align: middle;">clear</i>
                    Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Material Issue 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">output</i>
                Material Issue List
            </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 material issue data...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    <table id="materialRequestsTable" class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width: 140px;">Issue Number</th>
                                <th style="min-width: 100px;">Date Issued</th>
                                <th style="min-width: 150px;">Project</th>
                                <th style="min-width: 120px;">Division</th>
                                <th style="min-width: 150px;">Issued To</th>
                                <th style="min-width: 80px;">Items</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">assignment</i>
                        Material Issue 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="requestDetailsContent">
                        <!-- Content will be loaded dynamically -->
                        <div class="text-center py-4">
                            <i class="material-icons text-muted" style="font-size: 48px;">assignment</i>
                            <div class="text-muted">Loading issued 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">
    <style>
        .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-dispatched {
            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

@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>
let materialRequestsTable;

$(document).ready(function() {
    initializeDataTable();

    // Entries per page change handler
    $('#entries-per-page').change(function() {
        materialRequestsTable.page.len($(this).val()).draw();
    });

});

function initializeDataTable() {
    materialRequestsTable = $('#materialRequestsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route('warehouse.inventory.material-issued') }}',
            data: function(d) {
                d.status = $('#filter_status').val();
                d.date_from = $('#filter_date_from').val();
                d.date_to = $('#filter_date_to').val();
                d.project = $('#filter_project').val();
            }
        },
        columns: [
            {
                data: 'issue_number',
                name: 'issue_number',
                render: function(data) {
                    return `<strong>${data}</strong>`;
                }
            },
            {
                data: 'date_issued',
                name: 'date_issued',
                render: function(data) {
                    return data;
                }
            },
            {
                data: 'project',
                name: 'project',
                render: function(data) {
                    return data || '<span class="text-muted">N/A</span>';
                }
            },
            {
                data: 'division',
                name: 'division',
                render: function(data) {
                    return data || '<span class="text-muted">N/A</span>';
                }
            },
            {
                data: 'issued_to',
                name: 'issued_to',
                render: function(data) {
                    return data || '<span class="text-muted">N/A</span>';
                }
            },
            {
                data: 'items_count',
                name: 'items_count',
                render: function(data) {
                    return `<span class="badge badge-light">${data} items</span>`;
                }
            },
            {
                data: 'status',
                name: 'status',
                render: function(data, type, row) {
                    let badgeClass = 'badge-secondary';
                    let icon = 'info';

                    switch(data.class) {
                        case 'warning':
                            badgeClass = 'badge-warning';
                            icon = 'pending';
                            break;
                        case 'info':
                            badgeClass = 'badge-info';
                            icon = 'schedule';
                            break;
                        case 'success':
                            badgeClass = 'badge-success';
                            icon = 'check_circle';
                            break;
                    }

                    return `<span class="badge ${badgeClass}">
                        <i class="material-icons" style="font-size: 12px;">${icon}</i>
                        ${data.label}
                    </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 material issued found',
            zeroRecords: 'No matching material issued found'
        },
        drawCallback: function(settings) {
            $('#entries-per-page').val(settings._iDisplayLength);
        }
    });
}

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

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

// Action functions - Material Issue page only needs view and print functionality

function viewRequest(id) {
    console.log('viewRequest called with id:', id);

    // Hide any existing modals first
    $('.modal').modal('hide');

    // Wait a moment then show the new modal
    setTimeout(() => {
        // Load request details in modal
        $('#viewDetailsModal').modal({
            backdrop: 'static',
            keyboard: true,
            show: true
        });

        // Ensure modal appears in correct position
        $('#viewDetailsModal').on('shown.bs.modal', function () {
            $(this).css('z-index', 1050);
            $('.modal-backdrop').css('z-index', 1040);
        });

        // Show loading state
        $('#requestDetailsContent').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 request details...</div>
            </div>
        `);

        // Fetch request details after modal is shown
        const url = `/warehouse/inventory/material-issued/${id}`;
        console.log('Making request to:', url);

        fetch(url, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').getAttribute('content') : '{{ csrf_token() }}'
        }
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data);

        if (data.success) {
            const request = data.data;
            $('#requestDetailsContent').html(`
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Request Number:</strong><br>
                        <span class="text-primary">${request.request_number}</span>
                    </div>
                    <div class="col-md-6">
                        <strong>Date:</strong><br>
                        ${request.request_date}
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Project:</strong><br>
                        ${request.project}
                    </div>
                    <div class="col-md-6">
                        <strong>Requested By:</strong><br>
                        ${request.requested_by}
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-12">
                        <strong>Items:</strong>
                        <div class="table-responsive mt-2">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Code</th>
                                        <th>Description</th>
                                        <th>Unit</th>
                                        <th>Requested</th>
                                        <th>Available</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${request.items.map(item => `
                                        <tr>
                                            <td>${item.item_code}</td>
                                            <td>${item.description}</td>
                                            <td>${item.unit}</td>
                                            <td>${item.quantity_requested}</td>
                                            <td>${item.quantity_available}</td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            `);
        } else {
            $('#requestDetailsContent').html(`
                <div class="alert alert-danger">
                    Error loading request details: ${data.message || 'Unknown error'}
                </div>
            `);
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        $('#requestDetailsContent').html(`
            <div class="alert alert-danger">
                Error loading request details: ${error.message}<br>
                <small>Check console for more details</small>
            </div>
        `);
    });
    }, 100);
}

function deleteRequest(id) {
    if (confirm('Are you sure you want to delete this material request? This action cannot be undone.')) {
        fetch(`{{ route('warehouse.inventory.material-issued', '') }}/${id}`, {
            method: 'DELETE',
            headers: {
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('Material request deleted successfully!', 'success');
                materialRequestsTable.ajax.reload();
            } else {
                showAlert('Error: ' + (data.message || 'Failed to delete request'), 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('Error deleting material request. Please try again.', 'danger');
        });
    }
}

function showAlert(message, type) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alert = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;">
            ${message}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    `;
    $('body').append(alert);
    setTimeout(() => $('.alert').alert('close'), 5000);
}

function printIssueNote(id) {
    console.log('printIssueNote called with id:', id);

    // Open print view in new window - using Laravel route helper
    const printUrl = '{{ route("warehouse.inventory.material-issued.print", ":id") }}'.replace(':id', id);
    console.log('Opening print URL:', printUrl);
    const printWindow = window.open(printUrl, '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');

    if (printWindow) {
        printWindow.focus();

        // Wait for content to load then print
        printWindow.addEventListener('load', function() {
            setTimeout(() => {
                printWindow.print();
            }, 1000);
        });
    } else {
        // Fallback: navigate to print page if popup blocked
        window.open(printUrl, '_blank');
    }
}
</script>
@endpush