@extends('layouts.admin-simple')

@section('title', 'Site Returns - ' . $project->project_number . ' - ' . $project->project_name)

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.site-return.index') }}">Site Returns</a></li>
    <li class="breadcrumb-item active">{{ $project->project_number }} - {{ $project->project_name }}</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">Site Returns</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Material returns from {{ $project->project_number }} - {{ $project->project_name }}</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.site-return.index') }}" class="btn btn-sm btn-outline-secondary mr-2" title="Back to Projects">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to Projects
            </a>

            <button type="button" onclick="exportProjectReturns({{ $project->id }})" class="btn btn-sm btn-info mr-2" title="Export project returns">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </button>

            <a href="{{ route('warehouse.site-return.create') }}?project_id={{ $project->id }}" class="btn btn-sm btn-primary" title="Add new return for this project">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                New Return
            </a>
        </div>
    </div>
@endsection

@section('content')
    <!-- Project Info Card -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">business</i>
                Project Information
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <strong>Project Name:</strong><br>
                    <span class="text-muted">{{ $project->project_name }}</span>
                </div>
                <div class="col-md-3">
                    <strong>Project Number:</strong><br>
                    <span class="text-muted">{{ $project->project_number ?: 'N/A' }}</span>
                </div>
                <div class="col-md-3">
                    <strong>Division:</strong><br>
                    <span class="text-muted">{{ $project->projectDivision->division_name ?? 'N/A' }}</span>
                </div>
                <div class="col-md-3">
                    <strong>Project ID:</strong><br>
                    <span class="text-muted">{{ $project->project_id ?: 'N/A' }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Total Returns"
                :value="$statistics['total_returns'] ?? 0"
                icon="assignment_return"
                color="warning"
                subtitle="All returns"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Material Requests"
                :value="$statistics['total_material_requests'] ?? 0"
                icon="assignment"
                color="primary"
                subtitle="With returns"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Items Returned"
                :value="number_format($statistics['total_items_returned'] ?? 0)"
                icon="inventory_2"
                color="success"
                subtitle="Total items"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Total Value (AED)"
                :value="number_format($statistics['total_value_returned'] ?? 0, 2)"
                icon="attach_money"
                color="info"
                subtitle="Return value"
                currency="true"
            />
        </div>
    </div>

    <!-- Material Returns Table -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">assignment_return</i>
                Material Returns
            </h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Material Request</th>
                            <th>Return Count</th>
                            <th>Latest Return Date</th>
                            <th>Status</th>
                            <th>Items Returned</th>
                            <th>Total Value (AED)</th>
                            <th class="text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @if($returns && $returns->count() > 0)
                            @foreach($returns as $return)
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="mr-3">
                                                <div class="bg-{{ $return->materialRequest ? 'info' : 'warning' }} text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 40px; height: 40px;">
                                                    <i class="material-icons" style="font-size: 18px;">{{ $return->materialRequest ? 'assignment' : 'assignment_return' }}</i>
                                                </div>
                                            </div>
                                            <div>
                                                @if($return->materialRequest)
                                                    <div class="font-weight-medium">{{ $return->materialRequest->material_request_number ?: 'MR-' . str_pad($return->material_request_id, 6, '0', STR_PAD_LEFT) }}</div>
                                                    <small class="text-muted">{{ $return->materialRequest->requester->name ?? 'Unknown Requester' }}</small>
                                                @else
                                                    <div class="font-weight-medium">{{ $return->operation_number }}</div>
                                                    <small class="text-muted">Direct Return (No MR)</small>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge badge-primary">{{ $return->return_count }} {{ $return->return_count > 1 ? 'returns' : 'return' }}</span>
                                    </td>
                                    <td>{{ $return->latest_return_date ? \Carbon\Carbon::parse($return->latest_return_date)->format('d/m/Y H:i') : 'N/A' }}</td>
                                    <td>
                                        <span class="badge badge-{{
                                            $return->consolidated_status === 'completed' ? 'success' :
                                            ($return->consolidated_status === 'pending_processing' ? 'warning' :
                                            ($return->consolidated_status === 'processing' ? 'info' :
                                            ($return->consolidated_status === 'rejected' ? 'danger' : 'secondary')))
                                        }}">
                                            {{ ucfirst(str_replace('_', ' ', $return->consolidated_status)) }}
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge badge-outline-primary">{{ $return->total_returned_items }} items</span>
                                    </td>
                                    <td>
                                        <div class="text-right">
                                            <div class="font-weight-medium">AED {{ number_format($return->total_amount ?? 0, 2) }}</div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            @if($return->material_request_id)
                                                <a href="{{ route('warehouse.site-return.show-mr-returns', $return->material_request_id) }}" class="btn btn-sm btn-outline-primary" title="View Detailed Returns">
                                                    <i class="material-icons" style="font-size: 16px;">visibility</i>
                                                </a>
                                                <button onclick="printMRReturns({{ $return->material_request_id }})" class="btn btn-sm btn-outline-info" title="Print Returns">
                                                    <i class="material-icons" style="font-size: 16px;">print</i>
                                                </button>
                                            @else
                                                <a href="{{ route('warehouse.incoming-operations.show', $return->id) }}" class="btn btn-sm btn-outline-primary" title="View Return Details">
                                                    <i class="material-icons" style="font-size: 16px;">visibility</i>
                                                </a>
                                                <button onclick="printReturnNote({{ $return->id }})" class="btn btn-sm btn-outline-info" title="Print Return">
                                                    <i class="material-icons" style="font-size: 16px;">print</i>
                                                </button>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        @else
                            <tr>
                                <td colspan="7" class="text-center py-4">
                                    <i class="material-icons text-muted mb-3" style="font-size: 48px;">assignment_return</i>
                                    <h5 class="text-muted">No Returns Found</h5>
                                    <p class="text-muted mb-4">This project has no material returns yet.</p>
                                    <a href="{{ route('warehouse.site-return.create') }}?project_id={{ $project->id }}" class="btn btn-primary">
                                        <i class="material-icons mr-1">add</i>
                                        Create First Return
                                    </a>
                                </td>
                            </tr>
                        @endif
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    function exportProjectReturns(projectId) {
        window.location.href = `{{ route('warehouse.site-return.export') }}?project_id=${projectId}`;
    }

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

        // Open print view in new window - using Laravel route helper
        const printUrl = '{{ route("warehouse.site-return.print-mr-returns", ":id") }}'.replace(':id', materialRequestId);
        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');
        }
    }

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

        // Open print view in new window - using Laravel route helper
        const printUrl = '{{ route("warehouse.site-return.print-site-return", ":id") }}'.replace(':id', returnId);
        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