@extends('layouts.master')
@section('content')
<div class="container-fluid py-3">
    <div class="d-flex justify-content-end mb-3">
        <a href="{{ route('home') }}" class="btn-back">
            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
        </a>
    </div>

    <div class="row">
        <!-- Form Section -->
        <div class="col-lg-12">
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-primary text-white py-3">
                    <h5 class="mb-0" id="formTitle"><i class="fas fa-box me-2"></i> Process Inventory Journal</h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('inventory.journal.store') }}" method="POST" novalidate id="journalForm">
                        @csrf
                        <input type="hidden" name="id" id="entryId" value="">

                        <div id="timeout">
                            @if(Session::has('success'))
                                <p class="alert alert-info">{{ Session('success') }}</p>
                            @endif
                            @if(Session::has('error'))
                                <p class="alert alert-danger">{{ Session('error') }}</p>
                            @endif
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Date:</strong></label>
                                    <input type="date" name="date" class="form-control" id="date" value="{{ old('date', date('Y-m-d')) }}" required />
                                    @error('date')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Item:</strong></label>
                                    <select name="item_id" id="item_id" class="form-control" required>
                                        <option value="">Select Item</option>
                                        @foreach($items as $item)
                                            <option value="{{ $item->id }}" data-description="{{ $item->description1 }}" data-cost="{{ $item->cost }}" {{ old('item_id') == $item->id ? 'selected' : '' }}>
                                                {{ $item->code }} - {{ $item->description1 }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('item_id')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Warehouse:</strong></label>
                                    <select name="warehouse_id" id="warehouse_id" class="form-control" required>
                                        <option value="">Select Warehouse</option>
                                        @foreach($warehouses as $warehouse)
                                            <option value="{{ $warehouse->id }}" {{ old('warehouse_id') == $warehouse->id ? 'selected' : '' }}>
                                                {{ $warehouse->code }} - {{ $warehouse->description }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('warehouse_id')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>GL Control Account:</strong></label>
                                    <select name="gl_control_account_id" id="gl_control_account_id" class="form-control" required>
                                        <option value="">Select GL Account</option>
                                        @foreach($glAccounts as $account)
                                            <option value="{{ $account->id }}" {{ old('gl_control_account_id') == $account->id ? 'selected' : '' }}>
                                                {{ $account->code }} - {{ $account->account_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('gl_control_account_id')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Reference:</strong></label>
                                    <input class="form-control" type="text" name="reference" id="reference" value="{{ old('reference') }}" placeholder="Enter reference" required />
                                    @error('reference')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Description:</strong></label>
                                    <textarea class="form-control" name="description" id="description" placeholder="Enter description">{{ old('description') }}</textarea>
                                    @error('description')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Quantity In:</strong></label>
                                    <input class="form-control" type="number" step="0.01" name="quantity_in" id="quantity_in" value="{{ old('quantity_in') }}" placeholder="00.00" />
                                    @error('quantity_in')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Quantity Out:</strong></label>
                                    <input class="form-control" type="number" step="0.01" name="quantity_out" id="quantity_out" value="{{ old('quantity_out') }}" placeholder="00.00" />
                                    @error('quantity_out')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Unit Cost:</strong></label>
                                    <input class="form-control" type="number" step="0.01" name="unit_cost" id="unit_cost" value="{{ old('unit_cost') }}" placeholder="00.00" readonly />
                                    @error('unit_cost')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>New Unit Cost:</strong></label>
                                    <input class="form-control" type="number" step="0.01" name="new_unit_cost" id="new_unit_cost" value="{{ old('new_unit_cost') }}" placeholder="00.00" required />
                                    @error('new_unit_cost')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>UOM:</strong></label>
                                    <select name="uom_id" id="uom_id" class="form-control" required>
                                        <option value="">Select UOM</option>
                                        @foreach($uoms as $uom)
                                            <option value="{{ $uom->id }}" {{ old('uom_id') == $uom->id ? 'selected' : '' }}>
                                                {{ $uom->code }} - {{ $uom->description }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('uom_id')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Project:</strong></label>
                                    <select name="project_id" id="project_id" class="form-control">
                                        <option value="">Select Project (Optional)</option>
                                        @foreach($projects as $project)
                                            <option value="{{ $project->id }}" {{ old('project_id') == $project->id ? 'selected' : '' }}>
                                                {{ $project->code }} - {{ $project->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('project_id')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Currency:</strong></label>
                                    <select name="currency_id" id="currency_id" class="form-control" required>
                                        <option value="">Select Currency</option>
                                        @foreach($currencies as $currency)
                                            <option value="{{ $currency->id }}" {{ old('currency_id') == $currency->id ? 'selected' : '' }}>
                                                {{ $currency->code }} - {{ $currency->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('currency_id')<div class="text-danger small">{{ $message }}</div>@enderror
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button type="submit" id="submitButton" class="btn btn-primary me-2">Save</button>
                            <button type="reset" class="btn btn-outline-secondary" id="resetButton">Refresh</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Table Section -->
        <div class="col-lg-12 mt-4">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i> Journal Entries</h5>
                    @if($tempEntries->isNotEmpty())
                        <form action="{{ route('inventory.journal.process') }}" method="POST" class="m-0">
                            @csrf
                            <button type="submit" id="processJournalBtn" class="btn btn-success btn-sm">PROCESS ALL</button>
                        </form>
                    @endif
                </div>
                <div class="card-body">
                    @if($tempEntries->isEmpty())
                        <p class="text-muted mb-0">No journal entries available.</p>
                    @else
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date</th>
                                        <th>Item Code</th>
                                        <th>Item Description</th>
                                        <th>Warehouse</th>
                                        <th>Reference</th>
                                        <th>Qty In</th>
                                        <th>Qty Out</th>
                                        <th>Unit Cost</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($tempEntries as $entry)
                                    <tr>
                                        <td>{{ date('d/m/Y', strtotime($entry->date)) }}</td>
                                        <td>{{ $entry->item->code }}</td>
                                        <td>{{ $entry->item->description1 }}</td>
                                        <td>{{ $entry->warehouse->description }}</td>
                                        <td>{{ $entry->reference }}</td>
                                        <td>{{ number_format($entry->quantity_in, 2) }}</td>
                                        <td>{{ number_format($entry->quantity_out, 2) }}</td>
                                        <td>{{ number_format($entry->unit_cost, 2) }}</td>
                                        <td>
                                            @if($entry->status === 'Processed')
                                                <span class="badge bg-success">Processed</span>
                                            @else
                                                <span class="badge bg-warning text-dark">Open Journal</span>
                                            @endif
                                        </td>
                                        <td class="text-center">
                                            <a href="#" class="btn btn-sm btn-primary" onclick="editEntry({{ $entry->id }})">
                                                <i class="fas fa-edit"></i>
                                            </a>

                                            <!-- Process single entry -->
                                            @if($entry->status !== 'Processed')
                                            <form action="{{ route('inventory.journal.processSingle', $entry->id) }}" method="POST" class="d-inline">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-success process-btn">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            </form>
                                            @endif

                                            <!-- Delete button triggers modal -->
                                            <button class="btn btn-sm btn-danger deleteBtn" data-id="{{ $entry->id }}">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" id="deleteForm">
            @csrf
            @method('DELETE')
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">Are you sure you want to delete this journal entry?</div>
                <div class="modal-footer">
                    <button id="cancelDeleteBtn" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button id="confirmDeleteBtn" type="submit" class="btn btn-danger">Delete</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const bsModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
        const deleteForm = document.getElementById('deleteForm');

        document.querySelectorAll('.deleteBtn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                const entryId = this.getAttribute('data-id');
                const url = '{{ url("inventory-journal/delete") }}/' + entryId;
                deleteForm.setAttribute('action', url);
                bsModal.show();
            });
        });

        // Auto-populate item description and cost when item is selected
        document.getElementById('item_id').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const description = selectedOption.getAttribute('data-description');
            const cost = selectedOption.getAttribute('data-cost');
            
            document.getElementById('unit_cost').value = cost || '0.00';
            document.getElementById('new_unit_cost').value = cost || '0.00';
        });

        // Custom validation for quantity fields
        document.getElementById('journalForm').addEventListener('submit', function(e) {
            const quantityIn = parseFloat(document.getElementById('quantity_in').value) || 0;
            const quantityOut = parseFloat(document.getElementById('quantity_out').value) || 0;
            
            if (quantityIn <= 0 && quantityOut <= 0) {
                e.preventDefault();
                alert('Please enter at least one quantity (In or Out)');
                return false;
            }
        });
    });

    function editEntry(id) {
        fetch('{{ url("inventory-journal/edit") }}/' + id)
            .then(response => response.json())
            .then(entry => {
                document.getElementById('entryId').value = entry.id;
                document.getElementById('date').value = entry.date;
                document.getElementById('item_id').value = entry.item_id;
                document.getElementById('warehouse_id').value = entry.warehouse_id;
                document.getElementById('gl_control_account_id').value = entry.gl_control_account_id;
                document.getElementById('reference').value = entry.reference;
                document.getElementById('description').value = entry.description;
                document.getElementById('project_id').value = entry.project_id;
                document.getElementById('uom_id').value = entry.uom_id;
                document.getElementById('currency_id').value = entry.currency_id;
                document.getElementById('unit_cost').value = entry.unit_cost;
                document.getElementById('new_unit_cost').value = entry.unit_cost;
                document.getElementById('quantity_in').value = entry.quantity_in;
                document.getElementById('quantity_out').value = entry.quantity_out;

                document.getElementById('formTitle').innerHTML = '<i class="fas fa-box me-2"></i> Edit Inventory Journal Entry';
                document.getElementById('submitButton').textContent = 'Update';
                document.getElementById('journalForm').action = '{{ route("inventory.journal.update") }}';

                window.scrollTo({ top: 0, behavior: 'smooth' });
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading entry data');
            });
    }

    document.getElementById('resetButton').addEventListener('click', function() {
        document.getElementById('entryId').value = '';
        document.getElementById('formTitle').innerHTML = '<i class="fas fa-box me-2"></i> Process Inventory Journal';
        document.getElementById('submitButton').textContent = 'Save';
        document.getElementById('journalForm').action = '{{ route("inventory.journal.store") }}';
        document.getElementById('unit_cost').value = '';
        document.getElementById('new_unit_cost').value = '';
        document.getElementById('quantity_in').value = '';
        document.getElementById('quantity_out').value = '';
    });

    setTimeout(() => {
        document.querySelectorAll('.alert').forEach(alert => alert.style.display = 'none');
    }, 5000);
</script>

<style>
.btn-back {
    text-decoration: none;
    color: #1AB9D9;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    padding: 5px 15px;
    border-radius: 4px;
    transition: all 0.3s;
}
.btn-back:hover {
    background-color: rgba(26, 185, 217, 0.1);
    text-decoration: none;
}
.card {
    border-radius: 8px;
    overflow: hidden;
    border: none;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
}
.card-header {
    border-bottom: 1px solid rgba(0,0,0,0.1);
    padding: 12px 20px;
}
.table th {
    background-color: #f8f9fa;
}
#processJournalBtn {
    background-color: #ffffff !important;
    color: #1AB9D9 !important;
    border: 1px solid rgba(26,185,217,0.35) !important;
    font-weight: 600 !important;
    padding: 7px 14px !important;
    box-shadow: none !important;
    line-height: 1 !important;
}
#processJournalBtn:hover {
    background-color: #f5fbfc !important;
    color: #1498b0 !important;
    border-color: rgba(20,152,176,0.45) !important;
}
.table .process-btn {
    background-color: #1AB9D9 !important;
    border: 1px solid rgba(26,185,217,0.35) !important;
    color: #fff !important;
}
.table .process-btn:hover {
    background-color: #1498b0 !important;
    border-color: rgba(20,152,176,0.45) !important;
}
.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

@media (max-width: 768px) {
    table.table {
        font-size: 0.85rem;
    }
    table.table th,
    table.table td {
        white-space: nowrap;
    }
}

.text-danger.small {
    font-size: 0.85rem;
}
</style>
@endsection