@extends('layouts.admin-simple')

@section('title', 'Approve & Dispatch Material Issue')

@section('content')
<div class="container-fluid px-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-2 text-gray-800">
                        <i class="material-icons align-middle mr-2">local_shipping</i>
                        Approve & Dispatch Material Issue
                    </h1>
                    <p class="text-muted mb-0">Review, approve and dispatch material issue items in one step</p>
                </div>
                <div>
                    <a href="{{ route('warehouse.inventory.material-issued') }}" class="btn btn-secondary">
                        <i class="material-icons mr-1">arrow_back</i>
                        Back to List
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Error Messages -->
    @if($errors->any())
        <div class="alert alert-danger">
            <ul class="mb-0">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <!-- Success Message -->
    @if(session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <!-- Request Information Card -->
    <div class="card shadow mb-4">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="material-icons align-middle mr-1">assignment</i>
                Request Information
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <strong>Issue Number:</strong><br>
                    <span class="text-primary">{{ $materialRequest['request_number'] ?? 'N/A' }}</span>
                </div>
                <div class="col-md-3">
                    <strong>Date:</strong><br>
                    {{ $materialRequest['request_date'] ?? 'N/A' }}
                </div>
                <div class="col-md-3">
                    <strong>Project:</strong><br>
                    {{ $materialRequest['project'] ?? 'N/A' }}
                </div>
                <div class="col-md-3">
                    <strong>Requested By:</strong><br>
                    {{ $materialRequest['requested_by'] ?? 'N/A' }}
                </div>
            </div>
        </div>
    </div>

    <!-- Dispatch Form -->
    <div class="card shadow">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="material-icons align-middle mr-1">local_shipping</i>
                Dispatch Details
            </h6>
        </div>
        <div class="card-body">
            <form action="{{ route('warehouse.inventory.material-issued.process-dispatch', $materialRequest['id']) }}" method="POST" id="dispatchForm">
                @csrf

                <!-- Action Type - Always approve for pending requests -->
                <input type="hidden" name="action" value="approve" id="action_type">

                <!-- Dispatch Information -->
                <div class="row mb-4">
                    <div class="col-12">
                        <h6 class="font-weight-bold text-secondary mb-3">
                            <i class="material-icons align-middle mr-1">info</i>
                            Dispatch Information
                        </h6>
                        <div class="row">
                            <!-- Dispatch Date -->
                            <div class="col-md-4 mb-3">
                                <label for="dispatch_date" class="form-label">Dispatch Date <span class="text-danger">*</span></label>
                                <input type="date"
                                       class="form-control @error('dispatch_date') is-invalid @enderror"
                                       id="dispatch_date"
                                       name="dispatch_date"
                                       value="{{ old('dispatch_date', date('Y-m-d')) }}"
                                       required>
                                @error('dispatch_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <!-- Received By -->
                            <div class="col-md-4 mb-3">
                                @php
                                    $materialIssueReceiverOptions = [['value' => '', 'text' => 'Select Receiver']];
                                    if(isset($users)) {
                                        foreach($users as $user) {
                                            $materialIssueReceiverOptions[] = [
                                                'value' => $user->id,
                                                'text' => $user->name
                                            ];
                                        }
                                    }
                                @endphp
                                <x-warehouse.select2-dropdown
                                    name="received_by"
                                    id="received_by"
                                    label="Received By"
                                    placeholder="Select Receiver"
                                    :options="$materialIssueReceiverOptions"
                                    :selected="old('received_by')"
                                    required="true"
                                    errorField="received_by"
                                />
                            </div>

                            <!-- Dispatch Status -->
                            <div class="col-md-4 mb-3">
                                <x-warehouse.select2-dropdown
                                    name="dispatch_status"
                                    id="dispatch_status"
                                    label="Dispatch Status"
                                    placeholder="Select Status"
                                    :options="[
                                        ['value' => '', 'text' => 'Select Status'],
                                        ['value' => 'partially_dispatched', 'text' => 'Partially Dispatched'],
                                        ['value' => 'fully_dispatched', 'text' => 'Fully Dispatched']
                                    ]"
                                    :selected="old('dispatch_status')"
                                    required="true"
                                    errorField="dispatch_status"
                                />
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-4">

                <!-- Items Section -->
                <div class="row">
                    <div class="col-12">
                        <h6 class="font-weight-bold text-secondary mb-3">
                            <i class="material-icons align-middle mr-1">inventory_2</i>
                            Items Dispatch
                        </h6>

                        <!-- Items Table -->
                        <div class="table-responsive">
                            <table class="table table-hover" id="dispatch_items_table">
                                <thead class="thead-light">
                                    <tr>
                                        <th style="width: 100px;">Item Code</th>
                                        <th>Description</th>
                                        <th style="width: 80px;">Unit</th>
                                        <th style="width: 100px;">Available</th>
                                        <th style="width: 100px;">Requested</th>
                                        <th style="width: 100px;">Qty Issued</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if(isset($materialRequest['items']))
                                        @foreach($materialRequest['items'] as $index => $item)
                                            <tr>
                                                <td>
                                                    <span class="font-weight-bold text-primary">{{ $item['item_code'] }}</span>
                                                </td>
                                                <td>
                                                    <div class="text-truncate" style="max-width: 200px;" title="{{ $item['description'] }}">
                                                        {{ $item['description'] }}
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <span class="badge badge-secondary">{{ $item['unit'] }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="text-{{ ($item['quantity_available'] ?? 0) > 0 ? 'success' : 'danger' }} font-weight-bold">
                                                        {{ $item['quantity_available'] ?? 0 }}
                                                    </span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="font-weight-bold">{{ $item['quantity_requested'] ?? 0 }}</span>
                                                </td>
                                                <td>
                                                    <input type="hidden" name="items[{{ $index }}][item_id]" value="{{ $item['id'] }}">
                                                    <input type="number"
                                                           class="form-control form-control-sm"
                                                           name="items[{{ $index }}][quantity_approved]"
                                                           value="{{ old('items.' . $index . '.quantity_approved', $item['quantity_requested'] ?? 0) }}"
                                                           min="0"
                                                           max="{{ min($item['quantity_requested'] ?? 0, $item['quantity_available'] ?? 0) }}"
                                                           style="width: 80px;"
                                                           required>
                                                </td>
                                            </tr>
                                        @endforeach
                                    @else
                                        <tr>
                                            <td colspan="6" class="text-center text-muted">No items found for this request</td>
                                        </tr>
                                    @endif
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <hr class="my-4">
                <div class="row">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="text-muted">
                                <i class="material-icons align-middle mr-1">info</i>
                                <strong>Items:</strong> <span id="total_items_display">{{ isset($materialRequest['items']) ? count($materialRequest['items']) : 0 }} items</span>
                            </div>
                            <div>
                                <a href="{{ route('warehouse.inventory.material-issued') }}" class="btn btn-outline-secondary mr-2">
                                    <i class="material-icons mr-1">arrow_back</i>
                                    Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="material-icons mr-1">check_circle</i>
                                    Approve & Dispatch
                                </button>
                                <button type="button" class="btn btn-danger ml-2" onclick="cancelIssueRequest()">
                                    <i class="material-icons mr-1">cancel</i>
                                    Cancel Request
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Information Card -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-left-info">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                <i class="material-icons align-middle mr-1">info</i>
                                Dispatch Process
                            </div>
                            <div class="text-gray-800">
                                <ul class="mb-0 pl-3">
                                    <li>Review the requested items and quantities below</li>
                                    <li>Adjust the issued quantities based on availability</li>
                                    <li>Select appropriate dispatch status (partial/full)</li>
                                    <li>Specify who will receive the materials</li>
                                    <li>Inventory levels will be updated automatically upon dispatch</li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="material-icons fa-2x text-gray-300">local_shipping</i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Form submission validation
    document.getElementById('dispatchForm').addEventListener('submit', function(e) {
        const approvedInputs = document.querySelectorAll('input[name*="[quantity_approved]"]');
        let hasValidQuantity = false;

        approvedInputs.forEach(input => {
            if (parseInt(input.value) > 0) {
                hasValidQuantity = true;
            }
        });

        if (!hasValidQuantity) {
            e.preventDefault();
            alert('Please specify at least one item quantity to approve/dispatch');
            return false;
        }
    });

    // Auto-update dispatch status based on quantities
    document.querySelectorAll('input[name*="[quantity_approved]"]').forEach(input => {
        input.addEventListener('change', function() {
            updateDispatchStatus();
        });
    });
});

function updateDispatchStatus() {
    const statusSelect = document.getElementById('dispatch_status');
    const approvedInputs = document.querySelectorAll('input[name*="[quantity_approved]"]');

    let totalRequested = 0;
    let totalApproved = 0;
    let hasPartialApproval = false;

    approvedInputs.forEach((input, index) => {
        const requested = parseInt(input.max) || 0;
        const approved = parseInt(input.value) || 0;

        totalRequested += requested;
        totalApproved += approved;

        if (approved > 0 && approved < requested) {
            hasPartialApproval = true;
        }
    });

    // Auto-select dispatch status based on quantities
    if (totalApproved === 0) {
        statusSelect.value = '';
    } else if (hasPartialApproval || totalApproved < totalRequested) {
        statusSelect.value = 'partially_dispatched';
    } else if (totalApproved === totalRequested) {
        statusSelect.value = 'fully_dispatched';
    }
}

// Cancel issue request function
function cancelIssueRequest() {
    if (confirm('Are you sure you want to cancel this material issue? This action cannot be undone.')) {
        // Create a form to submit the cancel action
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = document.getElementById('dispatchForm').action;

        // Add CSRF token
        const csrfToken = document.createElement('input');
        csrfToken.type = 'hidden';
        csrfToken.name = '_token';
        csrfToken.value = '{{ csrf_token() }}';
        form.appendChild(csrfToken);

        // Add action input
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'cancel';
        form.appendChild(actionInput);

        // Submit the form
        document.body.appendChild(form);
        form.submit();
    }
}
</script>
@endpush