@extends('layouts.app')

@section('title', 'Manufacturing Demo')

@section('content')
<div class="page-content">
    <div class="row">
        <div class="col-md-12">
            <div class="page-title-box">
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('manufacturing.index') }}">Manufacturing</a></li>
                        <li class="breadcrumb-item active">Demo</li>
                    </ol>
                </div>
                <h4 class="page-title">Manufacturing Demo</h4>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="header-title">Complete Manufacturing Workflow Demo</h4>
                    <p class="text-muted mb-0">This demo will create a complete manufacturing workflow: Work Order → Material Issues → FG Receipt → Quality Check</p>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="alert alert-info">
                                <h5><i class="fas fa-info-circle"></i> Demo Overview</h5>
                                <p>This demo will:</p>
                                <ul>
                                    <li>Create a Work Order for 5 x 10km cables</li>
                                    <li>Issue raw materials (Copper Wire & Dana)</li>
                                    <li>Receive finished goods</li>
                                    <li>Create a final quality check</li>
                                    <li>Update stock balances and ledger</li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="alert alert-warning">
                                <h5><i class="fas fa-exclamation-triangle"></i> Prerequisites</h5>
                                <p>Make sure you have:</p>
                                <ul>
                                    <li>WMS Demo data seeded (warehouses, bins, UoMs)</li>
                                    <li>Product Management data (items, BOMs)</li>
                                    <li>Initial stock for raw materials</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div class="text-center mt-4">
                        <button id="run-demo-btn" class="btn btn-primary btn-lg">
                            <i class="fas fa-play"></i> Run Manufacturing Demo
                        </button>
                    </div>

                    <div id="demo-results" class="mt-4" style="display: none;">
                        <div class="alert alert-success">
                            <h5><i class="fas fa-check-circle"></i> Demo Completed Successfully!</h5>
                            <p id="demo-message"></p>
                        </div>
                    </div>

                    <div id="demo-error" class="mt-4" style="display: none;">
                        <div class="alert alert-danger">
                            <h5><i class="fas fa-times-circle"></i> Demo Failed</h5>
                            <p id="error-message"></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4 class="header-title">Current Stock Balances</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="stock-table" class="table table-striped table-centered mb-0">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>Warehouse</th>
                                    <th>Bin</th>
                                    <th>On Hand</th>
                                    <th>Value</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4 class="header-title">Manufacturing Ledger</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="ledger-table" class="table table-striped table-centered mb-0">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Item</th>
                                    <th>Qty Change</th>
                                    <th>Reference</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-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>
@endpush

@push('plugin-styles')
<link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
@endpush

@push('scripts')
<script>
(function() {
    'use strict';

    $(document).ready(function() {
        // Initialize DataTables
        const stockTable = $('#stock-table').DataTable({
            processing: true,
            serverSide: false,
            ajax: '{{ route("manufacturing.stock-data") }}',
            columns: [
                {data: 'item_name', name: 'item_name'},
                {data: 'warehouse_name', name: 'warehouse_name'},
                {data: 'bin_name', name: 'bin_name'},
                {data: 'on_hand_qty', name: 'on_hand_qty'},
                {data: 'total_value', name: 'total_value'}
            ],
            order: [[0, 'asc']],
            pageLength: 10,
            language: {
                search: "Search:",
                lengthMenu: "Show _MENU_ entries per page",
                info: "Showing _START_ to _END_ of _TOTAL_ entries",
                infoEmpty: "Showing 0 to 0 of 0 entries",
                infoFiltered: "(filtered from _MAX_ total entries)",
                processing: "Processing...",
                emptyTable: "No stock balances found"
            }
        });

        const ledgerTable = $('#ledger-table').DataTable({
            processing: true,
            serverSide: false,
            ajax: '{{ route("manufacturing.ledger-data") }}',
            columns: [
                {data: 'occurred_at', name: 'occurred_at'},
                {data: 'txn_type_label', name: 'txn_type'},
                {data: 'item_name', name: 'item_name'},
                {data: 'qty_change', name: 'qty_change'},
                {data: 'ref_no', name: 'ref_no'}
            ],
            order: [[0, 'desc']],
            pageLength: 10,
            language: {
                search: "Search:",
                lengthMenu: "Show _MENU_ entries per page",
                info: "Showing _START_ to _END_ of _TOTAL_ entries",
                infoEmpty: "Showing 0 to 0 of 0 entries",
                infoFiltered: "(filtered from _MAX_ total entries)",
                processing: "Processing...",
                emptyTable: "No ledger entries found"
            }
        });

        // Run Demo Button
        $('#run-demo-btn').off().on('click', function() {
            const btn = $(this);
            const originalText = btn.html();

            btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Running Demo...');

            $.ajax({
                url: '{{ route("manufacturing.demo.run") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    if (response.success) {
                        $('#demo-message').text(response.message);
                        $('#demo-results').show();
                        $('#demo-error').hide();

                        // Refresh tables
                        stockTable.ajax.reload();
                        ledgerTable.ajax.reload();

                        // Show success message
                        Swal.fire({
                            title: 'Success!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        });
                    } else {
                        throw new Error(response.message);
                    }
                },
                error: function(xhr) {
                    let errorMessage = 'An error occurred while running the demo.';

                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.message) {
                            errorMessage = response.message;
                        }
                    } catch (e) {
                        // Use default error message
                    }

                    $('#error-message').text(errorMessage);
                    $('#demo-error').show();
                    $('#demo-results').hide();

                    // Show error message
                    Swal.fire({
                        title: 'Error!',
                        text: errorMessage,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                },
                complete: function() {
                    btn.prop('disabled', false).html(originalText);
                }
            });
        });
    });
})();
</script>
@endpush
