@extends('layouts.admin-simple')

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

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.material-issue.index') }}">Material Issue</a></li>
    <li class="breadcrumb-item active">Decision</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 Decision</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Choose issue method for material request</p>
        </div>
        <div class="page-actions-right">
            <a href="{{ route('warehouse.material-issue.index') }}" class="btn btn-outline-secondary">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to List
            </a>
        </div>
    </div>
@endsection

@section('content')
<div class="container-fluid">

    <!-- Request Information -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">assignment</i>
                        Material Request Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Request Number</label>
                                <div class="text-primary font-weight-bold">
                                    {{ $transaction->material_request_number ?: 'MR-' . str_pad($transaction->id, 6, '0', STR_PAD_LEFT) }}
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Request Date</label>
                                <div>{{ $transaction->transaction_date->format('d-M-Y') }}</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Project</label>
                                <div>{{ $transaction->project->project_name ?? 'N/A' }}</div>
                                @if($transaction->division)
                                    <small class="text-muted">{{ $transaction->division->division_name }}</small>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Requested By</label>
                                <div>{{ $transaction->requester->name ?? 'N/A' }}</div>
                            </div>
                        </div>
                    </div>

                    <!-- Request Items -->
                    <div class="mt-4">
                        <h6 class="mb-3">
                            <i class="material-icons mr-2">shopping_cart</i>
                            Requested Items ({{ $transaction->items->count() }})
                        </h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Item Code</th>
                                        <th>Description</th>
                                        <th>Requested Qty</th>
                                        <th>Unit</th>
                                        <th>Available Stock</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($transaction->items as $item)
                                        <tr>
                                            <td>{{ $item->item->item_code ?? 'N/A' }}</td>
                                            <td>{{ $item->item->item_description ?? 'N/A' }}</td>
                                            <td>{{ number_format($item->quantity_requested, 2) }}</td>
                                            <td>{{ $item->item->unit_of_measure ?? 'PCS' }}</td>
                                            <td>
                                                @php
                                                    $availableStock = \App\Models\Warehouse\Inventory::where('item_id', $item->item_id)
                                                        ->where('quantity_available', '>', 0)
                                                        ->sum('quantity_available') ?: 0;
                                                    $stockClass = $availableStock >= $item->quantity_requested ? 'text-success' : 'text-danger';
                                                @endphp
                                                <span class="{{ $stockClass }}">{{ number_format($availableStock, 2) }}</span>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Issue Type Selection -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">compare_arrows</i>
                        Select Issue Method
                    </h6>
                </div>
                <div class="card-body">
                    <!-- Issue Type Selector -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="issue-type-option" onclick="selectIssueType('inventory_dispatch')">
                                <input type="radio" name="issue_type" id="inventory_dispatch" value="inventory_dispatch" class="d-none">
                                <label for="inventory_dispatch" class="issue-type-card">
                                    <div class="icon-wrapper bg-success">
                                        <i class="material-icons">inventory</i>
                                    </div>
                                    <h6 class="mt-3 mb-2">Inventory Dispatch</h6>
                                    <p class="text-muted small mb-0">Issue materials directly from warehouse inventory</p>
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="issue-type-option" onclick="selectIssueType('direct_delivery')">
                                <input type="radio" name="issue_type" id="direct_delivery" value="direct_delivery" class="d-none">
                                <label for="direct_delivery" class="issue-type-card">
                                    <div class="icon-wrapper bg-info">
                                        <i class="material-icons">local_shipping</i>
                                    </div>
                                    <h6 class="mt-3 mb-2">Direct Delivery</h6>
                                    <p class="text-muted small mb-0">Order from supplier and deliver directly to site</p>
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="issue-type-option" onclick="selectIssueType('project_transfer')">
                                <input type="radio" name="issue_type" id="project_transfer" value="project_transfer" class="d-none">
                                <label for="project_transfer" class="issue-type-card">
                                    <div class="icon-wrapper bg-primary">
                                        <i class="material-icons">swap_horiz</i>
                                    </div>
                                    <h6 class="mt-3 mb-2">Project Transfer</h6>
                                    <p class="text-muted small mb-0">Transfer materials from another project</p>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Dynamic Forms Container -->
                    <div id="dynamicFormContainer">
                        <div class="text-center text-muted py-5">
                            <i class="material-icons mb-3" style="font-size: 48px;">touch_app</i>
                            <h6>Select an issue method above to continue</h6>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Hidden forms that will be shown based on selection -->
<div style="display: none;">
    <!-- Inventory Dispatch Form -->
    <div id="inventoryDispatchForm">
        <form action="{{ route('warehouse.material-issue.process-decision', $transaction->id) }}" method="POST">
            @csrf
            <input type="hidden" name="issue_type" value="inventory_dispatch">

            <div class="border-top pt-4">
                <h6 class="mb-3">
                    <i class="material-icons mr-2">inventory</i>
                    Inventory Dispatch Details
                </h6>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="dispatch_date">Dispatch Date <span class="text-danger">*</span></label>
                            <input type="date" name="dispatch_date" id="dispatch_date" class="form-control"
                                   value="{{ date('Y-m-d') }}" min="{{ date('Y-m-d') }}" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="receiver_name">Receiver Name <span class="text-danger">*</span></label>
                            <input type="text" name="receiver_name" id="receiver_name" class="form-control" required>
                        </div>
                    </div>
                </div>

                <!-- Items with release quantities -->
                <div class="mt-4">
                    <h6 class="mb-3">Items to Issue</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>Requested</th>
                                    <th>Available</th>
                                    <th>Quantity to Issue</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($transaction->items as $item)
                                    @php
                                        $availableStock = \App\Models\Warehouse\Inventory::where('item_id', $item->item_id)
                                            ->where('quantity_available', '>', 0)
                                            ->sum('quantity_available') ?: 0;
                                        $maxIssue = min($item->quantity_requested, $availableStock);
                                    @endphp
                                    <tr>
                                        <td>
                                            <strong>{{ $item->item->item_code ?? 'N/A' }}</strong><br>
                                            <small>{{ $item->item->item_description ?? 'N/A' }}</small>
                                        </td>
                                        <td>{{ number_format($item->quantity_requested, 2) }}</td>
                                        <td>
                                            <span class="{{ $availableStock >= $item->quantity_requested ? 'text-success' : 'text-danger' }}">
                                                {{ number_format($availableStock, 2) }}
                                            </span>
                                        </td>
                                        <td>
                                            <input type="number" name="items[{{ $item->item_id }}][quantity_to_issue]"
                                                   class="form-control" step="0.01" min="0" max="{{ $maxIssue }}"
                                                   value="{{ $maxIssue }}" required>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="form-group mt-3">
                    <label for="dispatch_notes">Notes</label>
                    <textarea name="notes" id="dispatch_notes" class="form-control" rows="3"></textarea>
                </div>

                <div class="text-right mt-4">
                    <button type="button" onclick="clearSelection()" class="btn btn-secondary mr-2">Cancel</button>
                    <button type="submit" class="btn btn-success">
                        <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                        Process Inventory Dispatch
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Direct Delivery Form -->
    <div id="directDeliveryForm">
        <form action="{{ route('warehouse.material-issue.process-decision', $transaction->id) }}" method="POST">
            @csrf
            <input type="hidden" name="issue_type" value="direct_delivery">

            <div class="border-top pt-4">
                <h6 class="mb-3">
                    <i class="material-icons mr-2">local_shipping</i>
                    Direct Delivery Details
                </h6>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="supplier_id">Supplier</label>
                            <select name="supplier_id" id="supplier_id" class="form-control">
                                <option value="">Select Supplier (Optional)</option>
                                @foreach($suppliers as $supplier)
                                    <option value="{{ $supplier->id }}">{{ $supplier->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="delivery_date">Expected Delivery Date <span class="text-danger">*</span></label>
                            <input type="date" name="delivery_date" id="delivery_date" class="form-control"
                                   value="{{ date('Y-m-d', strtotime('+7 days')) }}" required>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="purchase_order_number">Purchase Order Number</label>
                    <input type="text" name="purchase_order_number" id="purchase_order_number" class="form-control">
                </div>

                <div class="form-group">
                    <label for="delivery_notes">Notes</label>
                    <textarea name="notes" id="delivery_notes" class="form-control" rows="3"></textarea>
                </div>

                <div class="text-right mt-4">
                    <button type="button" onclick="clearSelection()" class="btn btn-secondary mr-2">Cancel</button>
                    <button type="submit" class="btn btn-info">
                        <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                        Create Direct Delivery
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Project Transfer Form -->
    <div id="projectTransferForm">
        <form action="{{ route('warehouse.material-issue.process-decision', $transaction->id) }}" method="POST">
            @csrf
            <input type="hidden" name="issue_type" value="project_transfer">

            <div class="border-top pt-4">
                <h6 class="mb-3">
                    <i class="material-icons mr-2">swap_horiz</i>
                    Project Transfer Details
                </h6>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="source_project_id">Source Project <span class="text-danger">*</span></label>
                            <select name="source_project_id" id="source_project_id" class="form-control" required>
                                <option value="">Select Source Project</option>
                                @foreach($projects as $project)
                                    <option value="{{ $project->id }}">{{ $project->project_name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="required_date">Required Date <span class="text-danger">*</span></label>
                            <input type="date" name="required_date" id="required_date" class="form-control"
                                   value="{{ date('Y-m-d', strtotime('+3 days')) }}" min="{{ date('Y-m-d', strtotime('+1 day')) }}" required>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="priority">Priority <span class="text-danger">*</span></label>
                            <select name="priority" id="priority" class="form-control" required>
                                <option value="medium">Medium</option>
                                <option value="high">High</option>
                                <option value="urgent">Urgent</option>
                                <option value="low">Low</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="transfer_reason">Transfer Reason <span class="text-danger">*</span></label>
                            <input type="text" name="transfer_reason" id="transfer_reason" class="form-control"
                                   value="Material shortage - transfer from surplus project" required>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="transfer_notes">Notes</label>
                    <textarea name="notes" id="transfer_notes" class="form-control" rows="3"></textarea>
                </div>

                <div class="text-right mt-4">
                    <button type="button" onclick="clearSelection()" class="btn btn-secondary mr-2">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                        Create Transfer Request
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

@push('styles')
<style>
.info-item label {
    font-size: 12px;
    color: #6c757d;
    text-transform: uppercase;
    font-weight: 600;
    margin-bottom: 2px;
}

.issue-type-option {
    cursor: pointer;
}

.issue-type-card {
    display: block;
    padding: 2rem 1.5rem;
    border: 2px solid #e9ecef;
    border-radius: 0.5rem;
    text-align: center;
    transition: all 0.3s ease;
    cursor: pointer;
    height: 100%;
}

.issue-type-card:hover {
    border-color: #007bff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    text-decoration: none;
}

.issue-type-card.selected {
    border-color: #007bff;
    background-color: #f8f9ff;
    box-shadow: 0 4px 12px rgba(0,123,255,0.15);
}

.icon-wrapper {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    color: white;
}

.icon-wrapper i {
    font-size: 28px;
}

.issue-type-card h6 {
    color: #495057;
    font-weight: 600;
}

.issue-type-card.selected h6 {
    color: #007bff;
}
</style>
@endpush

@push('scripts')
<script>
function selectIssueType(type) {
    // Clear previous selections
    document.querySelectorAll('.issue-type-card').forEach(card => {
        card.classList.remove('selected');
    });

    document.querySelectorAll('input[name="issue_type"]').forEach(input => {
        input.checked = false;
    });

    // Set new selection
    document.getElementById(type).checked = true;
    document.querySelector(`label[for="${type}"]`).classList.add('selected');

    // Show the appropriate form
    showForm(type);
}

function showForm(type) {
    const container = document.getElementById('dynamicFormContainer');

    let formHtml = '';
    switch(type) {
        case 'inventory_dispatch':
            formHtml = document.getElementById('inventoryDispatchForm').innerHTML;
            break;
        case 'direct_delivery':
            formHtml = document.getElementById('directDeliveryForm').innerHTML;
            break;
        case 'project_transfer':
            formHtml = document.getElementById('projectTransferForm').innerHTML;
            break;
    }

    container.innerHTML = formHtml;
}

function clearSelection() {
    document.querySelectorAll('.issue-type-card').forEach(card => {
        card.classList.remove('selected');
    });

    document.querySelectorAll('input[name="issue_type"]').forEach(input => {
        input.checked = false;
    });

    document.getElementById('dynamicFormContainer').innerHTML = `
        <div class="text-center text-muted py-5">
            <i class="material-icons mb-3" style="font-size: 48px;">touch_app</i>
            <h6>Select a fulfillment method above to continue</h6>
        </div>
    `;
}
</script>
@endpush