@extends('layouts.app')

@section('title', 'Stock Ledger')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Stock Ledger</h4>
                    <div class="card-tools">
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exportModal">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- Filters -->
                    <div class="row mb-3">
                        <div class="col-md-2">
                            <label for="item_filter" class="form-label">Item</label>
                            @include('common.item-select', [
                                'name' => 'item_filter',
                                'id' => 'item_filter',
                                'label' => 'Item',
                                'class' => 'form-select form-select-sm',
                                'placeholder' => 'All Items',
                                'allowClear' => true
                            ])
                        </div>
                        <div class="col-md-2">
                            <label for="bin_filter" class="form-label">Bin</label>
                            <select id="bin_filter" class="form-select form-select-sm">
                                <option value="">All Bins</option>
                                @foreach($bins as $bin)
                                    <option value="{{ $bin->id }}">{{ $bin->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="txn_type_filter" class="form-label">Transaction Type</label>
                            <select id="txn_type_filter" class="form-select form-select-sm">
                                <option value="">All Types</option>
                                <option value="grn">Goods Received</option>
                                <option value="transfer">Stock Transfer</option>
                                <option value="production_issue">Production Issue</option>
                                <option value="production_receipt">Production Receipt</option>
                                <option value="adjustment">Stock Adjustment</option>
                                <option value="cycle_count">Cycle Count</option>
                                <option value="igp">Inward Gate Pass</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="date_from" class="form-label">Date From</label>
                            <input type="date" id="date_from" class="form-control form-control-sm">
                        </div>
                        <div class="col-md-2">
                            <label for="date_to" class="form-label">Date To</label>
                            <input type="date" id="date_to" class="form-control form-control-sm">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <div>
                                <button type="button" id="apply_filters" class="btn btn-primary btn-sm">
                                    <i class="fas fa-filter"></i> Apply
                                </button>
                                <button type="button" id="clear_filters" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-times"></i> Clear
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Ledger Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card bg-primary text-white">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="card-title">Total Transactions</h6>
                                            <h3 id="total_transactions">0</h3>
                                        </div>
                                        <div class="align-self-center">
                                            <i class="fas fa-exchange-alt fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-success text-white">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="card-title">Total In</h6>
                                            <h3 id="total_in">0</h3>
                                        </div>
                                        <div class="align-self-center">
                                            <i class="fas fa-arrow-down fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-danger text-white">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="card-title">Total Out</h6>
                                            <h3 id="total_out">0</h3>
                                        </div>
                                        <div class="align-self-center">
                                            <i class="fas fa-arrow-up fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-info text-white">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6 class="card-title">Net Movement</h6>
                                            <h3 id="net_movement">0</h3>
                                        </div>
                                        <div class="align-self-center">
                                            <i class="fas fa-balance-scale fa-2x"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Ledger Table -->
                    <div class="table-responsive">
                        <table id="ledgerTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Date & Time</th>
                                    <th>Item</th>
                                    <th>SKU</th>
                                    <th>Bin</th>
                                    <th>Lot No</th>
                                    <th>Transaction Type</th>
                                    <th>Reference</th>
                                    <th>Qty In</th>
                                    <th>Qty Out</th>
                                    <th>Net Qty</th>
                                    <th>Unit Cost</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Export Modal -->
<div class="modal fade" id="exportModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Export Ledger Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="export_format" class="form-label">Export Format</label>
                    <select id="export_format" class="form-select">
                        <option value="excel">Excel (.xlsx)</option>
                        <option value="csv">CSV</option>
                        <option value="pdf">PDF</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="export_filters" class="form-label">Include Current Filters</label>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="export_filters" checked>
                        <label class="form-check-label" for="export_filters">
                            Apply current filters to export
                        </label>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="export_data" class="btn btn-primary">Export</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css">
<style>
    .ledger-summary-card {
        transition: transform 0.2s;
    }
    .ledger-summary-card:hover {
        transform: translateY(-2px);
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    // Set default dates (last 30 days)
    var today = new Date();
    var thirtyDaysAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000));

    $('#date_from').val(thirtyDaysAgo.toISOString().split('T')[0]);
    $('#date_to').val(today.toISOString().split('T')[0]);

    // Initialize DataTable
    var table = $('#ledgerTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: '{{ route("stock-ledgers.get-data") }}',
            data: function(d) {
                d.item_id = $('#item_filter').val();
                d.bin_id = $('#bin_filter').val();
                d.txn_type = $('#txn_type_filter').val();
                d.date_from = $('#date_from').val();
                d.date_to = $('#date_to').val();
            }
        },
        columns: [
            { data: 'occurred_at', name: 'occurred_at' },
            { data: 'item_name', name: 'item_name' },
            { data: 'item_sku', name: 'item_sku' },
            { data: 'bin_name', name: 'bin_name' },
            { data: 'lot_no', name: 'lot_no' },
            { data: 'txn_type', name: 'txn_type' },
            { data: 'ref_no', name: 'ref_no' },
            { data: 'qty_in', name: 'qty_in' },
            { data: 'qty_out', name: 'qty_out' },
            { data: 'net_quantity', name: 'net_quantity' },
            { data: 'unit_cost', name: 'unit_cost' },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ],
        order: [[0, 'desc']],
        pageLength: 50,
        responsive: true
    });

    // Apply filters
    $('#apply_filters').click(function() {
        table.ajax.reload();
        updateSummaryCounts();
    });

    // Clear filters
    $('#clear_filters').click(function() {
        $('#item_filter').val('');
        $('#bin_filter').val('');
        $('#txn_type_filter').val('');
        $('#date_from').val(thirtyDaysAgo.toISOString().split('T')[0]);
        $('#date_to').val(today.toISOString().split('T')[0]);
        table.ajax.reload();
        updateSummaryCounts();
    });

    // Update summary counts
    function updateSummaryCounts() {
        $.ajax({
            url: '{{ route("stock-ledgers.get-data") }}',
            data: {
                item_id: $('#item_filter').val(),
                bin_id: $('#bin_filter').val(),
                txn_type: $('#txn_type_filter').val(),
                date_from: $('#date_from').val(),
                date_to: $('#date_to').val()
            },
            success: function(data) {
                var totalTransactions = data.data.length;
                var totalIn = data.data.reduce((sum, item) => sum + parseFloat(item.qty_in || 0), 0);
                var totalOut = data.data.reduce((sum, item) => sum + parseFloat(item.qty_out || 0), 0);
                var netMovement = totalIn - totalOut;

                $('#total_transactions').text(totalTransactions);
                $('#total_in').text(totalIn.toFixed(2));
                $('#total_out').text(totalOut.toFixed(2));
                $('#net_movement').text(netMovement.toFixed(2));

                // Color code net movement
                var netElement = $('#net_movement');
                if (netMovement > 0) {
                    netElement.removeClass('text-danger').addClass('text-success');
                } else if (netMovement < 0) {
                    netElement.removeClass('text-success').addClass('text-danger');
                } else {
                    netElement.removeClass('text-success text-danger');
                }
            }
        });
    }

    // Export functionality
    $('#export_data').click(function() {
        var format = $('#export_format').val();
        var includeFilters = $('#export_filters').is(':checked');

        var params = new URLSearchParams();
        params.append('format', format);
        params.append('include_filters', includeFilters);

        if (includeFilters) {
            params.append('item_id', $('#item_filter').val());
            params.append('bin_id', $('#bin_filter').val());
            params.append('txn_type', $('#txn_type_filter').val());
            params.append('date_from', $('#date_from').val());
            params.append('date_to', $('#date_to').val());
        }

        window.open('{{ route("stock-ledgers.export") }}?' + params.toString(), '_blank');
        $('#exportModal').modal('hide');
    });

    // Initial load
    updateSummaryCounts();
});
</script>
@endpush
