@extends('layouts.admin-simple')

@section('title', 'Create Site Return')

@push('styles')
<style>
.select2-container {
    width: 100% !important;
}

.select2-dropdown {
    min-width: 200px;
    max-width: 400px;
    width: auto !important;
}

.select2-container .select2-selection--single {
    min-width: 200px;
    max-width: 100%;
}

.select2-container--open .select2-dropdown--below {
    width: auto !important;
    min-width: 200px;
}

.info-section {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
}

.delivery-summary {
    border-left: 4px solid #dc3545;
    padding-left: 15px;
}

.return-reason-pending { background-color: #ffc107; }
.return-reason-good { background-color: #28a745; }
.return-reason-damaged { background-color: #fd7e14; }
.return-reason-defective { background-color: #dc3545; }
.return-reason-expired { background-color: #6c757d; }
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title mb-0">
                        <i class="material-icons mr-2">keyboard_return</i>
                        Create Site Return
                    </h4>
                </div>

                <!-- Delivery Summary -->
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="info-section delivery-summary">
                                <h6 class="font-weight-bold mb-3">Original Delivery Information</h6>
                                <p class="mb-1"><strong>Delivery #:</strong> {{ $directDelivery->delivery_number }}</p>
                                <p class="mb-1"><strong>Reference #:</strong> {{ $directDelivery->reference_number }}</p>
                                <p class="mb-1"><strong>Supplier:</strong>
                                    @if($directDelivery->supplier)
                                        {{ $directDelivery->supplier->name }}
                                    @else
                                        <span class="text-muted">Pending Supplier Selection</span>
                                    @endif
                                </p>
                                <p class="mb-1"><strong>Project:</strong> {{ $directDelivery->project->project_name }}</p>
                                <p class="mb-1"><strong>Delivery Date:</strong> {{ $directDelivery->delivery_date->format('M d, Y') }}</p>
                                <p class="mb-0"><strong>Status:</strong>
                                    <span class="badge badge-{{ $directDelivery->status_color }}">
                                        {{ ucfirst(str_replace('_', ' ', $directDelivery->status)) }}
                                    </span>
                                </p>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="info-section">
                                <h6 class="font-weight-bold mb-3">Return Instructions</h6>
                                <ul class="mb-0">
                                    <li>Select items to return from delivered items</li>
                                    <li>Specify return quantity (cannot exceed delivered quantity)</li>
                                    <li>Indicate condition of returned items</li>
                                    <li>Provide return reason for each item</li>
                                    <li>Returns will be processed as incoming operations</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Return Form -->
                <form action="{{ route('warehouse.direct-deliveries.process-site-return', $directDelivery) }}" method="POST">
                    @csrf
                    <div class="card-body border-top">
                        <!-- Return Details -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="return_date">Return Date <span class="text-danger">*</span></label>
                                    <input type="date" name="return_date" id="return_date"
                                           class="form-control @error('return_date') is-invalid @enderror"
                                           value="{{ old('return_date', date('Y-m-d')) }}" required>
                                    @error('return_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="return_reason">Overall Return Reason <span class="text-danger">*</span></label>
                                    <select name="return_reason" id="return_reason"
                                            class="form-control @error('return_reason') is-invalid @enderror" required>
                                        <option value="">Select Reason</option>
                                        <option value="excess_material" {{ old('return_reason') == 'excess_material' ? 'selected' : '' }}>Excess Material</option>
                                        <option value="wrong_specification" {{ old('return_reason') == 'wrong_specification' ? 'selected' : '' }}>Wrong Specification</option>
                                        <option value="quality_issue" {{ old('return_reason') == 'quality_issue' ? 'selected' : '' }}>Quality Issue</option>
                                        <option value="project_completion" {{ old('return_reason') == 'project_completion' ? 'selected' : '' }}>Project Completion</option>
                                        <option value="expired_material" {{ old('return_reason') == 'expired_material' ? 'selected' : '' }}>Expired Material</option>
                                        <option value="other" {{ old('return_reason') == 'other' ? 'selected' : '' }}>Other</option>
                                    </select>
                                    @error('return_reason')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="force_close">
                                        <input type="checkbox" name="force_close" id="force_close"
                                               value="1" {{ old('force_close') ? 'checked' : '' }}>
                                        Force Close Delivery
                                    </label>
                                    <small class="form-text text-muted">Mark delivery as fully returned (prevents future returns)</small>
                                </div>
                            </div>

                            <div class="col-md-6" id="force_close_reason_group" style="display: none;">
                                <div class="form-group">
                                    <label for="force_close_reason">Force Close Reason</label>
                                    <input type="text" name="force_close_reason" id="force_close_reason"
                                           class="form-control @error('force_close_reason') is-invalid @enderror"
                                           value="{{ old('force_close_reason') }}"
                                           placeholder="Reason for forcing delivery closure">
                                    @error('force_close_reason')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-12">
                                <div class="form-group">
                                    <label for="return_notes">Return Notes</label>
                                    <textarea name="return_notes" id="return_notes"
                                              class="form-control @error('return_notes') is-invalid @enderror"
                                              rows="3" placeholder="Additional notes about this return">{{ old('return_notes') }}</textarea>
                                    @error('return_notes')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Items to Return -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">assignment_return</i>
                                    Items Available for Return ({{ $returnableItems->count() }})
                                </h5>

                                @if($returnableItems->count() > 0)
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead class="thead-light">
                                            <tr>
                                                <th width="5%">
                                                    <input type="checkbox" id="select_all"> Select
                                                </th>
                                                <th width="25%">Item</th>
                                                <th width="10%">Delivered</th>
                                                <th width="10%">Available</th>
                                                <th width="10%">Return Qty</th>
                                                <th width="10%">Condition</th>
                                                <th width="15%">Return Reason</th>
                                                <th width="15%">Notes</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($returnableItems as $index => $item)
                                            <tr>
                                                <td class="text-center">
                                                    <input type="checkbox" name="items[{{ $index }}][selected]" value="1" class="item-checkbox">
                                                    <input type="hidden" name="items[{{ $index }}][item_id]" value="{{ $item->id }}">
                                                </td>
                                                <td>
                                                    <strong>{{ $item->item->item_description }}</strong>
                                                    @if($item->item->item_code)
                                                    <br><small class="text-muted">{{ $item->item->item_code }}</small>
                                                    @endif
                                                    @if($item->batch_number)
                                                    <br><small class="text-info">Batch: {{ $item->batch_number }}</small>
                                                    @endif
                                                    @if($item->expiry_date)
                                                    <br><small class="text-warning">Exp: {{ $item->expiry_date->format('M d, Y') }}</small>
                                                    @endif
                                                </td>
                                                <td class="text-center">
                                                    <strong>{{ number_format($item->received_quantity, 2) }}</strong>
                                                    @if($item->unit_of_measure)
                                                    <br><small class="text-muted">{{ $item->unit_of_measure }}</small>
                                                    @endif
                                                </td>
                                                <td class="text-center">
                                                    <strong class="text-success">{{ number_format($item->getAvailableForReturnQuantity(), 2) }}</strong>
                                                    <br><small class="text-muted">{{ $item->return_status }}</small>
                                                </td>
                                                <td>
                                                    <input type="number" name="items[{{ $index }}][return_quantity]"
                                                           class="form-control @error("items.{$index}.return_quantity") is-invalid @enderror"
                                                           step="0.01" min="0.01" max="{{ $item->getAvailableForReturnQuantity() }}"
                                                           value="{{ old("items.{$index}.return_quantity") }}" disabled>
                                                    @error("items.{$index}.return_quantity")
                                                    <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </td>
                                                <td>
                                                    <select name="items[{{ $index }}][condition]"
                                                            class="form-control @error("items.{$index}.condition") is-invalid @enderror" disabled>
                                                        <option value="">Select</option>
                                                        <option value="good" {{ old("items.{$index}.condition") == 'good' ? 'selected' : '' }}>Good</option>
                                                        <option value="damaged" {{ old("items.{$index}.condition") == 'damaged' ? 'selected' : '' }}>Damaged</option>
                                                        <option value="defective" {{ old("items.{$index}.condition") == 'defective' ? 'selected' : '' }}>Defective</option>
                                                        <option value="expired" {{ old("items.{$index}.condition") == 'expired' ? 'selected' : '' }}>Expired</option>
                                                    </select>
                                                    @error("items.{$index}.condition")
                                                    <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </td>
                                                <td>
                                                    <input type="text" name="items[{{ $index }}][return_reason]"
                                                           class="form-control @error("items.{$index}.return_reason") is-invalid @enderror"
                                                           value="{{ old("items.{$index}.return_reason") }}"
                                                           placeholder="Item return reason" disabled>
                                                    @error("items.{$index}.return_reason")
                                                    <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </td>
                                                <td>
                                                    <textarea name="items[{{ $index }}][return_notes]"
                                                              class="form-control @error("items.{$index}.return_notes") is-invalid @enderror"
                                                              rows="2" placeholder="Item notes" disabled>{{ old("items.{$index}.return_notes") }}</textarea>
                                                    @error("items.{$index}.return_notes")
                                                    <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </td>
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                @else
                                <div class="alert alert-warning">
                                    <i class="material-icons mr-2">warning</i>
                                    No items are available for return. All delivered items may have already been returned or are not eligible for return.
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>

                    <div class="card-footer">
                        <div class="row">
                            <div class="col-md-6">
                                <a href="{{ route('warehouse.direct-deliveries.show', $directDelivery) }}" class="btn btn-secondary">
                                    <i class="material-icons mr-1">arrow_back</i>
                                    Back to Delivery
                                </a>
                            </div>
                            @if($returnableItems->count() > 0)
                            <div class="col-md-6 text-right">
                                <button type="button" class="btn btn-outline-warning mr-2" onclick="fillMaxQuantities()">
                                    <i class="material-icons mr-1">select_all</i>
                                    Fill Max Quantities
                                </button>
                                <button type="submit" class="btn btn-danger">
                                    <i class="material-icons mr-1">keyboard_return</i>
                                    Process Site Return
                                </button>
                            </div>
                            @endif
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Handle force close reason visibility
    $('#force_close').change(function() {
        if ($(this).is(':checked')) {
            $('#force_close_reason_group').show();
        } else {
            $('#force_close_reason_group').hide();
        }
    });

    // Handle select all checkbox
    $('#select_all').change(function() {
        const isChecked = $(this).is(':checked');
        $('.item-checkbox').prop('checked', isChecked);
        $('.item-checkbox').each(function() {
            toggleItemInputs(this);
        });
    });

    // Handle individual item checkbox
    $('.item-checkbox').change(function() {
        toggleItemInputs(this);
        updateSelectAllState();
    });

    function toggleItemInputs(checkbox) {
        const row = $(checkbox).closest('tr');
        const isChecked = $(checkbox).is(':checked');

        row.find('input[type="number"], select, input[type="text"], textarea').not(checkbox).prop('disabled', !isChecked);

        if (isChecked) {
            row.find('input[name*="[return_quantity]"]').attr('required', true);
            row.find('select[name*="[condition]"]').attr('required', true);
        } else {
            row.find('input[name*="[return_quantity]"]').removeAttr('required');
            row.find('select[name*="[condition]"]').removeAttr('required');
        }
    }

    function updateSelectAllState() {
        const totalCheckboxes = $('.item-checkbox').length;
        const checkedCheckboxes = $('.item-checkbox:checked').length;

        if (checkedCheckboxes === 0) {
            $('#select_all').prop('indeterminate', false).prop('checked', false);
        } else if (checkedCheckboxes === totalCheckboxes) {
            $('#select_all').prop('indeterminate', false).prop('checked', true);
        } else {
            $('#select_all').prop('indeterminate', true);
        }
    }
});

function fillMaxQuantities() {
    $('.item-checkbox:checked').each(function() {
        const row = $(this).closest('tr');
        const maxQty = parseFloat(row.find('td:nth-child(4) strong').text().replace(/,/g, ''));
        row.find('input[name*="[return_quantity]"]').val(maxQty);
    });
}
</script>
@endpush