@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    /* Select2 text color fix */
    .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice__display {
        color: #000000 !important;
    }
    .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice__remove {
        color: #000000 !important;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h5 mb-0 text-gray-800">UEPL | SKU Approval</h1>
    <div class="display-date">
        <span id="day">day</span>,
        <span id="daynum">00</span>
        <span id="month">month</span>
        <span id="year">0000</span>
    </div>
    <div class="display-time"></div>
</div>

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- SKU Approval Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-clipboard-check mr-2"></i> SKU Approval List
        </h6>
        <button class="btn btn-light btn-sm" data-toggle="modal" data-target="#approvalModal" title="Add New Approval">
            <i class="fas fa-plus mr-1"></i> Add Approval
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="approvalTable" class="table table-bordered table-striped table-sm" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr>
                        <th width="60">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 width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- DataTable fills -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Approval Modal -->
<div class="modal fade" id="approvalModal" tabindex="-1" role="dialog" aria-labelledby="approvalModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form id="approvalForm">
                @csrf
                <input type="hidden" id="approvalId">
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white" id="approvalModalLabel">
                        <i class="fas fa-plus-circle mr-2"></i> New SKU Approval
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Customer <span class="text-danger">*</span></label>
                            <select class="form-control" id="customer" name="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 mb-3">
                            <label class="small font-weight-bold">Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="date" name="date" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 mb-3">
                            <label class="small font-weight-bold">Items <span class="text-danger">*</span></label>
                            <select class="form-control select2-items" id="items" name="items[]" multiple required>
                                @foreach ($items as $id => $name)
                                    <option value="{{ $id }}">{{ $name }}</option>
                                @endforeach
                            </select>
                            <small class="text-muted">Search and select multiple items</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Approved Date</label>
                            <input type="date" class="form-control" id="approvedDate" name="approved_date">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Status <span class="text-danger">*</span></label>
                            <select class="form-control" id="approvedStatus" name="status" required>
                                <option value="Pending">Pending</option>
                                <option value="Approved">Approved</option>
                                <option value="Rejected">Rejected</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Action Date</label>
                            <input type="date" class="form-control" id="actionDate" name="action_date">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Action By</label>
                            <input type="text" class="form-control" id="actionBy" name="action_by">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Created By <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="createdBy" name="created_by" value="{{ auth()->user()->name ?? '' }}" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="small font-weight-bold">Stock Status <span class="text-danger">*</span></label>
                            <select class="form-control" id="stockStatus" name="stock_status" required>
                                <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 btn-sm" data-dismiss="modal">
                        <i class="fa fa-times mr-1"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" id="saveApproval">
                        <i class="fa fa-save mr-1"></i> Save Approval
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
let table;

$(document).ready(function() {
    // Initialize Select2 for items dropdown
    $('.select2-items').select2({
        theme: 'bootstrap-5',
        placeholder: 'Search and select items...',
        allowClear: true,
        width: '100%',
        dropdownParent: $('#approvalModal')
    });

    table = $('#approvalTable').DataTable({
        ajax: '{{ url("superadmin/skuapproval/list") }}',
        columns: [
            { data: 'id' },
            { data: 'customer' },
            { data: 'items' },
            { data: 'date' },
            { data: 'approved_date' },
            {
                data: 'status',
                render: function(data) {
                    if (data === 'Approved') {
                        return '<span class="badge badge-success">Approved</span>';
                    } else if (data === 'Rejected') {
                        return '<span class="badge badge-danger">Rejected</span>';
                    }
                    return '<span class="badge badge-warning">Pending</span>';
                }
            },
            { data: 'action_date' },
            { data: 'action_by' },
            { data: 'created_by' },
            {
                data: 'stock_status',
                render: function(data) {
                    if (data === 'In Stock') {
                        return '<span class="badge badge-success">In Stock</span>';
                    } else if (data === 'Out of Stock') {
                        return '<span class="badge badge-danger">Out of Stock</span>';
                    } else if (data === 'Low Stock') {
                        return '<span class="badge badge-warning">Low Stock</span>';
                    }
                    return '<span class="badge badge-info">' + (data || '-') + '</span>';
                }
            },
            {
                data: null,
                orderable: false,
                searchable: false,
                render: function(data, type, row) {
                    return `
                        <div class="text-center" style="white-space: nowrap;">
                            <button class="btn btn-warning btn-sm edit-btn" data-id="${row.id}" title="Edit">
                                <i class="fa fa-edit"></i>
                            </button>
                            <button class="btn btn-danger btn-sm delete-btn" data-id="${row.id}" title="Delete">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        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 approval records found"
        }
    });

    // Save Approval
    $('#saveApproval').click(function() {
        let id = $('#approvalId').val();
        let url = id ? '{{ url("superadmin/sku-approval") }}/' + id : '{{ url("superadmin/sku-approval") }}';
        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(response) {
                $('#approvalModal').modal('hide');
                $('#approvalForm')[0].reset();
                $('#approvalId').val('');
                $('#items').val(null).trigger('change'); // Reset Select2
                table.ajax.reload();
                Swal.fire('Success!', 'Approval saved successfully!', 'success');
            },
            error: function(xhr) {
                console.log(xhr.responseText);
                if (xhr.responseJSON) {
                    let errors = Object.values(xhr.responseJSON).flat().join('<br>');
                    Swal.fire('Validation Error', errors, 'error');
                } else {
                    Swal.fire('Error!', 'Error saving record', 'error');
                }
            }
        });
    });

    // Edit Approval
    $(document).on('click', '.edit-btn', function() {
        let id = $(this).data('id');
        $.get("{{ url('superadmin/sku-approval') }}/" + id, function(data) {
            $('#approvalId').val(data.id);
            $('#customer').val(data.customer_id);
            $('#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.map(String);
            } else if (typeof data.items === 'string') {
                items = data.items.split(',').map(i => i.trim());
            }
            $('#items').val(items).trigger('change'); // Update Select2
            $('#approvalModalLabel').html('<i class="fas fa-edit mr-2"></i> Edit SKU Approval');
            $('#approvalModal').modal('show');
        });
    });

    // Reset modal on close
    $('#approvalModal').on('hidden.bs.modal', function() {
        $('#approvalForm')[0].reset();
        $('#approvalId').val('');
        $('#approvalModalLabel').html('<i class="fas fa-plus-circle mr-2"></i> New SKU Approval');
        $('#items').val(null).trigger('change'); // Reset Select2
    });

    // Delete Approval
    $(document).on('click', '.delete-btn', function() {
        let id = $(this).data('id');
        Swal.fire({
            title: 'Delete Approval?',
            text: "Are you sure you want to delete this approval record?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Delete!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("superadmin/sku-approval") }}/' + id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function() {
                        table.ajax.reload();
                        Swal.fire('Deleted!', 'Approval record deleted successfully.', 'success');
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Delete failed!', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endsection
