@extends('layouts.dashboard.managerapp')

@section('title', 'SKU Approval')

@section('styles')
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
    <style>
        div.dt-buttons {
            float: left;
            display: flex !important;
        }

        .dt-buttons .btn {
            margin-right: 0.5rem !important;
            padding: 0.25rem 0.75rem !important;
            font-size: 0.95rem !important;
        }

        .action-btns .btn {
            margin-right: 0.25rem;
            margin-bottom: 0.1rem;
        }

        .btn {
            width: auto;
        }

        .modal .form-label {
            font-weight: 500;
        }

        .modal-footer .btn {
            min-width: 100px;
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid bg-white">
        <x-layout.page-header title="UEPL / SKU (Stock Keeping Unit)" icon="barcode" iconColor="info" />

        <div class="row">
            <div class="col-lg-12">
                <div class="container-fluid py-4 sku-approval">
                    <div class="row mb-4 align-items-center">
                        <div class="col-md-10">
                            <h2 class="mb-0"><i class="bi bi-box-arrow-in-right"></i> SKU Approval Management</h2>
                        </div>
                        <div class="col-md-2 text-end">
                            <button class="btn btn-primary" data-toggle="modal" data-target="#approvalModal">
                                <i class="bi bi-plus-circle"></i> Add Approval
                            </button>
                        </div>
                    </div>

                    <div class="card shadow mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-table"></i> SKU Approval List</span>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="approvalTable" class="table table-bordered table-striped table-hover w-100">
                                    <thead>
                                        <tr>
                                            <th>Approval ID</th>
                                            <th>Customer</th>
                                            <th>Items</th>
                                            <th>Date</th>
                                            <th>Approved Date</th>
                                            <th>Status</th>
                                            <th>Action Date</th>
                                            <th>Action By</th>
                                            <th>Created By</th>
                                            <th>Stock Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- DataTable fills -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Approval Modal -->
                <div class="modal fade" id="approvalModal" tabindex="-1" aria-labelledby="approvalModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <form id="approvalForm">
                                @csrf
                                <input type="hidden" id="approvalId">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="approvalModalLabel">New SKU Approval</h5>
                                    <button type="button" class="close btn" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Customer</label>
                                            <select class="form-control" id="customer" required>
                                                <option value="">Select Customer</option>
                                                @foreach ($customers as $id => $name)
                                                    <option value="{{ $id }}">{{ $name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Date</label>
                                            <input type="date" class="form-control" id="date" required>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-12">
                                            <label class="form-label">Items</label>
                                            <select class="form-control" id="items" multiple required>
                                                @foreach ($items as $id => $name)
                                                    <option value="{{ $id }}">{{ $name }}</option>
                                                @endforeach
                                            </select>
                                            <small class="text-muted">You can select multiple items</small>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Approved Date</label>
                                            <input type="date" class="form-control" id="approvedDate">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Approved Status</label>
                                            <select class="form-select" id="approvedStatus">
                                                <option value="Pending">Pending</option>
                                                <option value="Approved">Approved</option>
                                                <option value="Rejected">Rejected</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Action Date</label>
                                            <input type="date" class="form-control" id="actionDate">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Action By</label>
                                            <input type="text" class="form-control" id="actionBy">
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Created By</label>
                                            <input type="text" class="form-control" id="createdBy" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Stock Status</label>
                                            <select class="form-select" id="stockStatus">
                                                <option value="In Stock">In Stock</option>
                                                <option value="Low Stock">Low Stock</option>
                                                <option value="Out of Stock">Out of Stock</option>
                                                <option value="Pre-order">Pre-order</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" id="saveApproval">Save
                                        Approval</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <!-- End Approval Modal -->

                <!-- Delete Confirmation Modal -->
                <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel"
                    aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-danger text-white">
                                <h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
                                <button type="button" class="close btn" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                Are you sure you want to delete this approval record? This action cannot be undone.
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                <button type="button" class="btn btn-danger" id="confirmDelete">Delete</button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- End Delete Modal -->
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script>
        let table, deleteId = null;
        $(document).ready(function() {
            table = $('#approvalTable').DataTable({
                ajax: '{{ route('manager.sku-approval.list') }}',
                columns: [{
                        data: 'id'
                    },
                    {
                        data: 'customer'
                    },
                    {
                        data: 'items'
                    },
                    {
                        data: 'date'
                    },
                    {
                        data: 'approved_date'
                    },
                    {
                        data: 'status'
                    },
                    {
                        data: 'action_date'
                    },
                    {
                        data: 'action_by'
                    },
                    {
                        data: 'created_by'
                    },
                    {
                        data: 'stock_status'
                    },
                    {
                        data: null,
                        className: "action-btns",
                        orderable: false,
                        searchable: false,
                        render: function(data, type, row) {
                            return `
                                <button class="btn btn-warning btn-sm edit-btn" data-id="${row.id}"><i class="bi bi-pencil-square"></i></button>
                                <button class="btn btn-danger btn-sm delete-btn" data-id="${row.id}"><i class="bi bi-trash"></i></button>
                            `;
                        }
                    }
                ],
                dom: 'Bfrtip',
                buttons: [{
                        extend: 'copy',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'csv',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'excel',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'pdf',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'print',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'colvis',
                        className: 'btn btn-secondary btn-sm'
                    }
                ],
                pageLength: 10,
                responsive: true,
                language: {
                    "emptyTable": "No approvals found"
                }
            });

            $('#saveApproval').click(function() {
                let id = $('#approvalId').val();
                let url = id ? '{{ url('/manager/sku-approval') }}/' + id :
                    '{{ route('manager.sku-approval.store') }}';
                let items = $('#items').val();
                if (Array.isArray(items)) items = items.join(',');
                let payload = {
                    _token: '{{ csrf_token() }}',
                    customer: $('#customer').val(),
                    items: items,
                    date: $('#date').val(),
                    approved_date: $('#approvedDate').val(),
                    status: $('#approvedStatus').val(),
                    action_date: $('#actionDate').val(),
                    action_by: $('#actionBy').val(),
                    created_by: $('#createdBy').val(),
                    stock_status: $('#stockStatus').val()
                };
                if (id) payload._method = 'PUT';

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: payload,
                    success: function() {
                        $('#approvalModal').modal('hide');
                        $('#approvalForm')[0].reset();
                        $('#items').val(null).trigger('change');
                        table.ajax.reload();
                        toastr.success('Saved!');
                    },
                    error: function(xhr) {
                        console.log(xhr.responseText);
                        let errors = xhr.responseJSON && xhr.responseJSON.errors;
                        if (errors) {
                            Object.values(errors).forEach(arr => toastr.error(arr[0]));
                        } else {
                            toastr.error('Error saving record');
                        }
                    }
                });
            });

            $(document).on('click', '.edit-btn', function() {
                let id = $(this).data('id');
                $.get("{{ url('/manager/sku-approval') }}/" + id, function(data) {
                    $('#approvalId').val(data.id);
                    $('#customer').val(data.customer_id).trigger('change'); // <-- FIXED HERE
                    $('#date').val(data.date);
                    $('#approvedDate').val(data.approved_date);
                    $('#approvedStatus').val(data.status);
                    $('#actionDate').val(data.action_date);
                    $('#actionBy').val(data.action_by);
                    $('#createdBy').val(data.created_by);
                    $('#stockStatus').val(data.stock_status);

                    let items = [];
                    if (Array.isArray(data.items)) {
                        items = data.items;
                    } else if (typeof data.items === 'string') {
                        items = data.items.split(',').map(i => i.trim());
                    }
                    $('#items').val(items).trigger('change');
                    $('#approvalModalLabel').text('Edit SKU Approval');
                    $('#approvalModal').modal('show');
                });
            });


            $('#approvalModal').on('hidden.bs.modal', function() {
                $('#approvalForm')[0].reset();
                $('#approvalId').val('');
                $('#approvalModalLabel').text('New SKU Approval');
                $('#items').val(null).trigger('change');
            });

            $(document).on('click', '.delete-btn', function() {
                deleteId = $(this).data('id');
                $('#deleteModal').modal('show');
            });

            $('#confirmDelete').click(function() {
                if (deleteId) {
                    $.ajax({
                        url: '{{ url('/manager/sku-approval') }}/' + deleteId,
                        type: 'DELETE',
                        data: {
                            _token: '{{ csrf_token() }}'
                        },
                        success: function() {
                            $('#deleteModal').modal('hide');
                            table.ajax.reload();
                            toastr.success('Deleted!');
                        },
                        error: function(xhr) {
                            toastr.error('Delete failed!');
                        }
                    });
                }
            });
        });
    </script>
@endpush
