@extends('layouts.admin-simple')

@section('title', 'Approve Transfer Request - ' . $transferRequest->transfer_request_number)

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.transfer-requests.index') }}">Transfer Requests</a></li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.transfer-requests.show', $transferRequest) }}">{{ $transferRequest->transfer_request_number }}</a></li>
    <li class="breadcrumb-item active">Approve</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">Approve Transfer Request</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">
                Request: {{ $transferRequest->transfer_request_number }} |
                Status: {{ ucwords(str_replace('_', ' ', $transferRequest->status)) }} |
                Priority: <span class="badge badge-{{ $transferRequest->priority_color }}">{{ ucfirst($transferRequest->priority) }}</span>
            </p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.transfer-requests.show', $transferRequest) }}" class="btn btn-sm btn-secondary mr-2">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to Request
            </a>
        </div>
    </div>
@endsection

@section('content')
<div class="container-fluid">
    <!-- Request Summary -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">info</i>
                        Transfer Details
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-sm-6">
                            <strong>From Project:</strong><br>
                            <span class="text-primary">{{ $transferRequest->transferrerProject->project_name }}</span>
                        </div>
                        <div class="col-sm-6">
                            <strong>To Project:</strong><br>
                            <span class="text-success">{{ $transferRequest->receiverProject->project_name }}</span>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-sm-6">
                            <strong>Requested By:</strong><br>
                            {{ $transferRequest->requestedBy->name ?? 'Unknown' }}
                        </div>
                        <div class="col-sm-6">
                            <strong>Request Date:</strong><br>
                            {{ $transferRequest->request_date->format('M d, Y') }}
                        </div>
                    </div>
                    @if($transferRequest->transfer_reason)
                    <hr>
                    <div>
                        <strong>Transfer Reason:</strong><br>
                        <span class="text-muted">{{ $transferRequest->transfer_reason }}</span>
                    </div>
                    @endif

                    @if($uniqueSourceReferences->isNotEmpty())
                    <hr>
                    <div>
                        <strong>Selected References:</strong><br>
                        @foreach($uniqueSourceReferences as $reference)
                            <div class="mb-1">
                                <span class="badge badge-{{ $reference['type'] == 'Material Request' ? 'info' : 'warning' }} mr-1">
                                    {{ $reference['type'] }}
                                </span>
                                <span class="text-primary font-weight-semibold">{{ $reference['number'] }}</span>
                                @if($reference['date'])
                                    <small class="text-muted">
                                        ({{ $reference['date']->format('M d, Y') }})
                                    </small>
                                @endif
                            </div>
                        @endforeach
                        <small class="text-muted">References selected when creating this transfer request</small>
                    </div>
                    @endif
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">assignment</i>
                        Approval Status
                    </h6>
                </div>
                <div class="card-body">
                    <div class="approval-status">
                        @if($transferRequest->status == 'pending_transferrer_approval')
                            <div class="alert alert-warning">
                                <i class="material-icons mr-2">schedule</i>
                                <strong>Awaiting Approval</strong><br>
                                <small>Review and approve/modify the quantities below</small>
                            </div>

                            @php
                                $hasInsufficientQuantity = false;
                                foreach($transferRequest->items as $item) {
                                    if($item->quantity_requested > $item->available_quantity) {
                                        $hasInsufficientQuantity = true;
                                        break;
                                    }
                                }
                            @endphp

                            @if($hasInsufficientQuantity)
                                <div class="alert alert-danger">
                                    <i class="material-icons mr-2">warning</i>
                                    <strong>Insufficient Inventory Alert</strong><br>
                                    <small>Some items have insufficient quantity available. Maximum transferable quantities have been applied.</small>
                                </div>
                            @endif
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Approval Form -->
    <form method="POST" action="{{ route('warehouse.transfer-requests.approve-transferrer', $transferRequest) }}" id="approvalForm">
        @csrf

        <!-- Items to Approve -->
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="material-icons mr-2">inventory_2</i>
                    Items for Approval
                    <span class="badge badge-primary ml-2">{{ $transferRequest->items->count() }} items</span>
                </h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" style="font-size: 16px;">
                        <thead>
                            <tr>
                                <th style="width: 25%">Item Description</th>
                                <th style="width: 10%">Item Code</th>
                                <th style="width: 7%">Unit</th>
                                <th style="width: 10%" class="text-center">Requested</th>
                                <th style="width: 10%" class="text-center">Previously Transferred</th>
                                <th style="width: 10%" class="text-center">Returned to Warehouse</th>
                                <th style="width: 13%" class="text-center">Additional Transfer</th>
                                <th style="width: 15%" class="text-center">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($transferRequest->items as $index => $item)
                            <tr data-item-id="{{ $item->item_id }}">
                                <td>
                                    <div class="d-flex align-items-center">
                                        <i class="material-icons mr-2 text-primary" style="font-size: 20px;">inventory_2</i>
                                        <div>
                                            <div class="font-weight-semibold">{{ $item->item->item_description }}</div>
                                            <small class="text-muted">{{ $item->item->item_code }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span style="color: #6c757d; font-weight: 500;">{{ $item->item->item_code }}</span>
                                </td>
                                <td>
                                    <span class="badge badge-secondary">{{ $item->item->unit_of_measure }}</span>
                                </td>
                                <td class="text-center">
                                    <strong class="text-info">{{ number_format($item->quantity_requested, 2) }}</strong>
                                </td>
                                <td class="text-center">
                                    @if($item->quantity_approved)
                                        <span class="badge badge-{{ $item->approval_status === 'approved' ? 'success' : ($item->approval_status === 'partial' ? 'warning' : 'secondary') }}">
                                            {{ number_format($item->quantity_approved, 2) }}
                                        </span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    @if($item->returned_to_warehouse > 0)
                                        <span class="text-warning">{{ number_format($item->returned_to_warehouse, 2) }}</span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    <div>
                                        <input type="number"
                                               name="item_approvals[{{ $item->item_id }}][quantity_approved]"
                                               class="form-control form-control-sm text-center quantity-input"
                                               value="{{ old('item_approvals.' . $item->item_id . '.quantity_approved', $item->remaining_from_source ?? 0) }}"
                                               min="0"
                                               max="{{ $item->remaining_from_source ?? 0 }}"
                                               step="0.01"
                                               onchange="updateItemStatus({{ $index }}, this.value, {{ $item->quantity_requested }})"
                                               onkeyup="validateQuantity(this, {{ $item->remaining_from_source ?? 0 }}, {{ $index }})"
                                               data-available="{{ $item->available_quantity }}"
                                               data-requested="{{ $item->quantity_requested }}"
                                               title="Max additional transfer: {{ number_format($item->remaining_from_source ?? 0, 2) }}">
                                        @php
                                            $remainingToApprove = max(0, $item->quantity_requested - ($item->quantity_approved ?? 0));
                                            $maxAdditional = min($remainingToApprove, $item->available_quantity);
                                        @endphp
                                        @if($maxAdditional < $remainingToApprove)
                                            <small class="text-warning d-block mt-1">
                                                <i class="material-icons" style="font-size: 12px;">warning</i>
                                                Max additional: {{ number_format($maxAdditional, 2) }}
                                            </small>
                                        @endif
                                        <span id="quantity-error-{{ $index }}" class="text-danger d-block small" style="display: none;"></span>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <span id="status-{{ $index }}" class="badge
                                        @if($item->quantity_approved == 0 || !$item->quantity_approved)
                                            badge-secondary">Pending
                                        @elseif($item->quantity_approved >= $item->quantity_requested)
                                            badge-success">Transferred
                                        @else
                                            badge-warning">Partially Transferred
                                        @endif
                                    </span>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Approval Notes -->
        <div class="card mt-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="material-icons mr-2">note</i>
                    Approval Notes
                </h6>
            </div>
            <div class="card-body">
                <div class="form-group">
                    <label for="approval_notes">Notes (Optional)</label>
                    <textarea name="approval_notes" id="approval_notes" rows="3" class="form-control"
                              placeholder="Add any comments or conditions for this approval...">{{ old('approval_notes') }}</textarea>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="card mt-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        <small>Review all quantities carefully before dispatching</small>
                    </div>
                    <div class="btn-group">
                        <button type="submit" name="action" value="approve" class="btn btn-success" onclick="return validateForm()">
                            <i class="material-icons mr-1" style="font-size: 16px;">local_shipping</i>
                            Dispatch Transfer
                        </button>
                        <button type="button" id="rejectAllBtn" class="btn btn-warning" onclick="setAllToZero()">
                            <i class="material-icons mr-1" style="font-size: 16px;">block</i>
                            Reject All
                        </button>
                        <button type="button" id="cancelTransferBtn" class="btn btn-danger" onclick="cancelTransfer()">
                            <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                            Cancel Transfer
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- Cancel Form -->
    <form method="POST" action="{{ route('warehouse.transfer-requests.cancel', $transferRequest) }}" id="cancelForm" style="display: none;">
        @csrf
        @method('DELETE')
    </form>
</div>

<script>
function validateQuantity(input, maxAvailable, index) {
    const value = parseFloat(input.value);
    const errorElement = document.getElementById(`quantity-error-${index}`);

    if (value > maxAvailable) {
        input.classList.add('is-invalid');
        errorElement.textContent = `Exceeds available quantity (${maxAvailable.toFixed(2)})`;
        errorElement.style.display = 'block';
        return false;
    } else {
        input.classList.remove('is-invalid');
        errorElement.style.display = 'none';
        return true;
    }
}

function validateForm() {
    let isValid = true;
    const inputs = document.querySelectorAll('.quantity-input');

    inputs.forEach((input, index) => {
        const maxAvailable = parseFloat(input.getAttribute('data-available'));
        const value = parseFloat(input.value);

        if (value > maxAvailable) {
            validateQuantity(input, maxAvailable, index);
            isValid = false;
        }
    });

    if (!isValid) {
        alert('Please correct the quantities that exceed available amounts before approving.');
    }

    return isValid;
}

function updateItemStatus(index, approvedQty, requestedQty) {
    const statusElement = document.getElementById(`status-${index}`);
    const approved = parseFloat(approvedQty);
    const requested = parseFloat(requestedQty);

    if (isNaN(approved) || approved === 0) {
        statusElement.className = 'badge badge-secondary';
        statusElement.textContent = 'Pending';
    } else if (approved < requested) {
        statusElement.className = 'badge badge-warning';
        statusElement.textContent = 'Partially Transferred';
    } else {
        statusElement.className = 'badge badge-success';
        statusElement.textContent = 'Transferred';
    }
}

function setAllToZero() {
    // Check if there are any partially approved items
    let hasPartiallyApproved = false;
    let hasExistingApprovals = false;

    document.querySelectorAll('.quantity-input').forEach((input) => {
        const existingApproval = parseFloat(input.closest('tr').querySelector('td:nth-child(5) .badge').textContent.replace(/[^\d.-]/g, '')) || 0;
        const requested = parseFloat(input.getAttribute('data-requested'));

        if (existingApproval > 0) {
            hasExistingApprovals = true;
            if (existingApproval < requested) {
                hasPartiallyApproved = true;
            }
        }
    });

    if (hasPartiallyApproved) {
        alert('Cannot reject items that are partially transferred. For partially transferred items, only "Approve Transfer" action is allowed.');
        return;
    }

    let confirmMessage = 'Are you sure you want to reject all items? This will set all approved quantities to zero.';

    if (hasExistingApprovals) {
        confirmMessage = 'WARNING: Some items have existing approvals.\n\nRejecting will reset all approvals to zero. Are you sure you want to proceed?';
    }

    if (confirm(confirmMessage)) {
        document.querySelectorAll('.quantity-input').forEach((input, index) => {
            input.value = 0;
            updateItemStatus(index, 0, parseFloat(input.getAttribute('data-requested')));
        });
    }
}

function cancelTransfer() {
    // Check if there are any partially approved items (both existing and new)
    let hasPartiallyApproved = false;
    let partiallyApprovedItems = [];
    let hasExistingApprovals = false;

    document.querySelectorAll('.quantity-input').forEach((input) => {
        const requested = parseFloat(input.getAttribute('data-requested'));
        const newApproval = parseFloat(input.value) || 0;

        // Check existing approvals from the "Previously Approved" column
        const existingApprovalElement = input.closest('tr').querySelector('td:nth-child(5) .badge');
        const existingApproval = existingApprovalElement ?
            parseFloat(existingApprovalElement.textContent.replace(/[^\d.-]/g, '')) || 0 : 0;

        const totalApproved = existingApproval + newApproval;

        if (existingApproval > 0) {
            hasExistingApprovals = true;
        }

        if (totalApproved > 0 && totalApproved < requested) {
            hasPartiallyApproved = true;
            const itemRow = input.closest('tr');
            const itemDescription = itemRow.querySelector('.font-weight-semibold').textContent;
            partiallyApprovedItems.push({
                name: itemDescription,
                requested: requested,
                totalApproved: totalApproved,
                existingApproval: existingApproval,
                newApproval: newApproval
            });
        }
    });

    let confirmMessage = '';

    if (hasPartiallyApproved) {
        confirmMessage = 'WARNING: This transfer request has partially transferred items.\n\n';
        confirmMessage += 'Cancelling is NOT allowed for partially transferred items.\n';
        confirmMessage += 'For partially transferred items, only "Approve Transfer" action is available.\n\n';
        confirmMessage += 'If you proceed with cancellation, the following will happen:\n';
        confirmMessage += '• Status will change to "TRANSFERRED"\n';
        confirmMessage += '• Requested quantities will be adjusted to match the transferred quantities\n\n';
        confirmMessage += 'Affected items:\n';

        partiallyApprovedItems.forEach(item => {
            confirmMessage += `• ${item.name}:\n`;
            confirmMessage += `  Originally Requested: ${item.requested}\n`;
            confirmMessage += `  Total Approved: ${item.totalApproved}\n`;
            confirmMessage += `  → Final Request will be: ${item.totalApproved}\n\n`;
        });

        confirmMessage += 'Are you sure you want to proceed with this action?\n';
        confirmMessage += 'This will effectively approve the transfer with the current transferred quantities.';

        if (confirm(confirmMessage)) {
            // Submit the form but with a special parameter to indicate partial approval finalization
            const form = document.getElementById('cancelForm');
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'finalize_partial_approval';
            hiddenInput.value = '1';
            form.appendChild(hiddenInput);
            form.submit();
        }
    } else if (hasExistingApprovals) {
        confirmMessage = 'WARNING: This transfer request has some approved items.\n\n';
        confirmMessage += 'If you cancel now:\n';
        confirmMessage += '• All approvals will be reverted\n';
        confirmMessage += '• The transfer request will be cancelled\n';
        confirmMessage += '• This action cannot be undone\n\n';
        confirmMessage += 'Are you sure you want to cancel this transfer request?';

        if (confirm(confirmMessage)) {
            document.getElementById('cancelForm').submit();
        }
    } else {
        confirmMessage = 'Are you sure you want to cancel this transfer request? This action cannot be undone.';

        if (confirm(confirmMessage)) {
            document.getElementById('cancelForm').submit();
        }
    }
}

// Check if any items are partially approved and update button states
function updateButtonStates() {
    let hasPartiallyApproved = false;

    document.querySelectorAll('.quantity-input').forEach((input) => {
        const existingApprovalElement = input.closest('tr').querySelector('td:nth-child(5) .badge');
        const existingApproval = existingApprovalElement ?
            parseFloat(existingApprovalElement.textContent.replace(/[^\d.-]/g, '')) || 0 : 0;
        const requested = parseFloat(input.getAttribute('data-requested'));

        if (existingApproval > 0 && existingApproval < requested) {
            hasPartiallyApproved = true;
        }
    });

    const rejectAllBtn = document.getElementById('rejectAllBtn');
    if (hasPartiallyApproved) {
        rejectAllBtn.disabled = true;
        rejectAllBtn.title = 'Cannot reject items that are partially transferred';
        rejectAllBtn.classList.add('disabled');
    } else {
        rejectAllBtn.disabled = false;
        rejectAllBtn.title = '';
        rejectAllBtn.classList.remove('disabled');
    }
}

// Initialize status on page load
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.quantity-input').forEach((input, index) => {
        const requested = parseFloat(input.getAttribute('data-requested'));
        updateItemStatus(index, input.value, requested);

        // Check if requested quantity exceeds available
        const available = parseFloat(input.getAttribute('data-available'));
        const originalRequested = parseFloat(input.getAttribute('onchange').match(/\d+(\.\d+)?/)[0]);
        if (originalRequested > available) {
            const row = input.closest('tr');
            if (!row.querySelector('.availability-warning')) {
                const warning = document.createElement('small');
                warning.className = 'text-warning availability-warning';
                warning.innerHTML = '<i class="material-icons" style="font-size: 12px;">warning</i> Insufficient quantity available';
                input.parentNode.appendChild(warning);
            }
        }
    });

    // Update button states based on partial approvals
    updateButtonStates();
});
</script>
@endsection