@extends('layouts.dashboard.superadminapp')

@section('title', 'Sales Order List')

@section('styles')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css">
<style>
    /* Compact Page Header */
    .page-header-compact {
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border-radius: 0.75rem;
        padding: 0.5rem 1.25rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1.25rem;
        border-left: 4px solid #10b981;
    }
    .page-header-compact h1 {
        font-size: 1.25rem;
        font-weight: 600;
        color: #1e293b;
        margin: 0;
    }
    .datetime-display {
        display: flex;
        align-items: center;
        gap: 1rem;
        font-size: 0.875rem;
        color: #64748b;
    }
    .datetime-display .time {
        font-family: 'Courier New', monospace;
        font-weight: 600;
        color: #10b981;
        background: #f0fdf4;
        padding: 0.25rem 0.75rem;
        border-radius: 0.375rem;
    }

    /* Modern Summary Cards with Gradient Backgrounds */
    .stat-card {
        background: #ffffff;
        border-radius: 0.75rem;
        padding: 1.25rem;
        transition: all 0.3s ease;
        border: none;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        height: 100%;
        position: relative;
        overflow: hidden;
    }
    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, var(--gradient-from) 0%, var(--gradient-to) 100%);
    }
    .stat-card.blue {
        --gradient-from: #3b82f6;
        --gradient-to: #2563eb;
        background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%);
    }
    .stat-card.amber {
        --gradient-from: #f59e0b;
        --gradient-to: #d97706;
        background: linear-gradient(135deg, #ffffff 0%, #fffbeb 100%);
    }
    .stat-card.green {
        --gradient-from: #10b981;
        --gradient-to: #059669;
        background: linear-gradient(135deg, #ffffff 0%, #ecfdf5 100%);
    }
    .stat-card.red {
        --gradient-from: #ef4444;
        --gradient-to: #dc2626;
        background: linear-gradient(135deg, #ffffff 0%, #fef2f2 100%);
    }
    .stat-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 24px rgba(0,0,0,0.15);
    }
    .stat-label {
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 0.5rem;
    }
    .stat-card.blue .stat-label { color: #2563eb; }
    .stat-card.amber .stat-label { color: #d97706; }
    .stat-card.green .stat-label { color: #059669; }
    .stat-card.red .stat-label { color: #dc2626; }
    .stat-value {
        font-size: 2rem;
        font-weight: 700;
        color: #1e293b;
        line-height: 1;
    }
    .stat-icon {
        font-size: 2.5rem;
        opacity: 0.15;
    }

    /* Alert Styling */
    .alert {
        border: none;
        border-radius: 0.75rem;
        padding: 1rem 1.25rem;
        margin-bottom: 1.25rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        border-left: 4px solid;
    }
    .alert-success {
        background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
        border-left-color: #10b981;
        color: #065f46;
    }
    .alert-danger {
        background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
        border-left-color: #ef4444;
        color: #991b1b;
    }

    /* DataTable Container with Gradient Header */
    .table-card {
        background: #ffffff;
        border-radius: 0.75rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        overflow: hidden;
        margin-bottom: 2rem;
    }
    .table-card-header {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #ffffff;
        padding: 1rem 1.5rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: none;
    }
    .table-card-header h5 {
        margin: 0;
        font-size: 1.125rem;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .table-card-body {
        padding: 1.5rem;
    }

    /* Modern DataTable Styling */
    #salesOrderTable {
        width: 100% !important;
        border-collapse: separate;
        border-spacing: 0;
    }
    #salesOrderTable thead th {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        color: #475569;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.5px;
        padding: 1rem 0.75rem;
        border: none;
        white-space: nowrap;
        border-bottom: 2px solid #e2e8f0;
    }
    #salesOrderTable tbody td {
        padding: 1rem 0.75rem;
        vertical-align: middle;
        border-bottom: 1px solid #f1f5f9;
        color: #475569;
        font-size: 0.875rem;
    }
    #salesOrderTable tbody tr {
        transition: all 0.2s ease;
    }
    #salesOrderTable tbody tr:hover {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        transform: scale(1.01);
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }

    /* Modern Badges */
    .badge {
        padding: 0.375rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    .badge-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #ffffff;
    }
    .badge-warning {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: #ffffff;
    }
    .badge-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: #ffffff;
    }

    /* Modern Action Buttons */
    .table-actions {
        display: flex;
        gap: 0.25rem;
        justify-content: center;
        flex-wrap: wrap;
    }
    .table-actions .btn {
        padding: 0.375rem 0.75rem;
        font-size: 0.75rem;
        border-radius: 0.375rem;
        border: none;
        transition: all 0.2s ease;
        font-weight: 500;
    }
    .table-actions .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
    .btn-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #ffffff;
    }
    .btn-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: #ffffff;
    }
    .btn-info {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        color: #ffffff;
    }
    .btn-secondary {
        background: linear-gradient(135deg, #64748b 0%, #475569 100%);
        color: #ffffff;
    }
    .btn-warning {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: #ffffff;
    }

    /* DataTable Export Buttons */
    .dt-buttons .btn {
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%) !important;
        border: 1px solid #e2e8f0 !important;
        color: #475569 !important;
        padding: 0.5rem 1rem !important;
        border-radius: 0.5rem !important;
        font-weight: 500 !important;
        transition: all 0.2s ease !important;
        margin-right: 0.5rem !important;
    }
    .dt-buttons .btn:hover {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
        color: #ffffff !important;
        border-color: #10b981 !important;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3) !important;
    }

    /* Modern Modals */
    .modal-content {
        border: none;
        border-radius: 1rem;
        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        overflow: hidden;
    }
    .modal-header {
        border: none;
        padding: 1.25rem 1.5rem;
        color: #ffffff;
    }
    .modal-header.bg-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    }
    .modal-header.bg-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }
    .modal-title {
        font-weight: 600;
        font-size: 1.125rem;
    }
    .modal-body {
        padding: 1.5rem;
        color: #475569;
    }
    .modal-footer {
        border-top: 1px solid #e2e8f0;
        padding: 1rem 1.5rem;
        background: #f8fafc;
    }

    /* Add New Button in Header */
    .btn-light {
        background: #ffffff !important;
        color: #10b981 !important;
        border: 2px solid #ffffff !important;
        font-weight: 600;
        padding: 0.5rem 1.25rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    .btn-light:hover {
        background: rgba(255,255,255,0.2) !important;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(255,255,255,0.3);
    }

    /* Toast Notifications */
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    .toast {
        animation: slideInRight 0.3s ease-out;
        border: none;
        border-radius: 0.75rem;
        box-shadow: 0 8px 24px rgba(0,0,0,0.15);
    }
    .toast.bg-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    }
    .toast.bg-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .stat-card {
            margin-bottom: 1rem;
        }
        .table-actions {
            flex-direction: column;
        }
    }
</style>
@endsection

@section('content')
    <!-- Compact Page Header -->
    <div class="page-header-compact">
        <div class="d-flex justify-content-between align-items-center flex-wrap">
            <h1><i class="fas fa-shopping-cart mr-2" style="color: #10b981;"></i>Sales Order List</h1>
            <div class="datetime-display">
                <span class="date"><i class="far fa-calendar mr-1"></i><span id="currentDate"></span></span>
                <span class="time"><i class="far fa-clock mr-1"></i><span id="currentTime"></span></span>
            </div>
        </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

    <!-- Modern Summary Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="stat-card blue">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="stat-label">Total Orders</div>
                        <div class="stat-value">{{ $orders->count() }}</div>
                    </div>
                    <i class="fas fa-file-invoice stat-icon text-primary"></i>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="stat-card amber">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="stat-label">Pending</div>
                        <div class="stat-value">{{ $orders->where('status', 'pending')->count() }}</div>
                    </div>
                    <i class="fas fa-clock stat-icon text-warning"></i>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="stat-card green">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="stat-label">Approved</div>
                        <div class="stat-value">{{ $orders->where('status', 'approved')->count() }}</div>
                    </div>
                    <i class="fas fa-check-circle stat-icon text-success"></i>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="stat-card red">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="stat-label">Rejected</div>
                        <div class="stat-value">{{ $orders->where('status', 'rejected')->count() }}</div>
                    </div>
                    <i class="fas fa-times-circle stat-icon text-danger"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Modern DataTable Card -->
    <div class="table-card">
        <div class="table-card-header">
            <h5><i class="fas fa-table mr-2"></i>Sales Orders</h5>
            <a href="{{ route('superadmin.sales.salesorder') }}" class="btn btn-light btn-sm">
                <i class="fa fa-plus-square mr-1"></i> Add New
            </a>
        </div>
        <div class="table-card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="salesOrderTable">
                    <thead>
                        <tr class="text-center">
                            <th style="width:5%">#</th>
                            <th style="width:15%">Sales Order No</th>
                            <th style="width:12%">Date</th>
                            <th style="width:20%">Company Name</th>
                            <th style="width:12%">Grand Total</th>
                            <th style="width:10%">Status</th>
                            <th style="width:20%">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($orders as $index => $order)
                            <tr id="row-{{ $order->id }}" class="text-center">
                                <td>{{ $index + 1 }}</td>
                                <td class="font-weight-bold">{{ $order->sales_order_no }}</td>
                                <td>{{ \Carbon\Carbon::parse($order->sales_order_date)->format('d M Y') }}</td>
                                <td class="text-left">{{ $order->customer ? $order->customer->company : '-' }}</td>
                                <td class="text-right font-weight-bold">₹{{ number_format($order->grand_total, 2) }}</td>
                                <td>
                                    @if($order->status === 'approved')
                                        <span class="badge badge-success">Approved</span>
                                    @elseif($order->status === 'rejected')
                                        <span class="badge badge-danger">Rejected</span>
                                    @else
                                        <span class="badge badge-warning">Pending</span>
                                    @endif
                                </td>
                                <td>
                                    <div class="table-actions">
                                        @if ($order->status === 'pending')
                                            <button class="btn btn-success approve-btn" data-id="{{ $order->id }}" data-so="{{ $order->sales_order_no }}" title="Approve">
                                                <i class="fa fa-check"></i>
                                            </button>
                                            <button class="btn btn-danger reject-btn" data-id="{{ $order->id }}" data-so="{{ $order->sales_order_no }}" title="Reject">
                                                <i class="fa fa-times"></i>
                                            </button>
                                        @endif
                                        <a href="{{ route('superadmin.sales.order.show', $order->id) }}" class="btn btn-info" title="View">
                                            <i class="fa fa-eye"></i>
                                        </a>
                                        <a href="{{ route('superadmin.sales.order.print', $order->id) }}" class="btn btn-secondary" target="_blank" title="Print">
                                            <i class="fa fa-print"></i>
                                        </a>
                                        <a href="{{ route('superadmin.sales.order.edit', $order->id) }}" class="btn btn-warning" title="Edit">
                                            <i class="fa fa-edit"></i>
                                        </a>
                                        <button class="btn btn-danger delete-btn" data-id="{{ $order->id }}" data-so="{{ $order->sales_order_no }}" title="Delete">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger">
                    <h6 class="modal-title mb-0"><i class="fas fa-exclamation-triangle mr-2"></i>Delete Sales Order</h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">Are you sure you want to delete this sales order?</p>
                    <p class="mb-0 font-weight-bold"><strong id="deleteItemName"></strong></p>
                    <small class="text-muted">This action cannot be undone.</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger btn-sm" id="confirmDeleteBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Delete</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Approve Confirmation Modal -->
    <div class="modal fade" id="approveModal" tabindex="-1" aria-labelledby="approveModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-success">
                    <h6 class="modal-title mb-0"><i class="fas fa-check-circle mr-2"></i>Approve Sales Order</h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">Are you sure you want to approve this sales order?</p>
                    <p class="mb-0 font-weight-bold"><strong id="approveItemName"></strong></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success btn-sm" id="confirmApproveBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Approve</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Reject Confirmation Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger">
                    <h6 class="modal-title mb-0"><i class="fas fa-times-circle mr-2"></i>Reject Sales Order</h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">Are you sure you want to reject this sales order?</p>
                    <p class="mb-0 font-weight-bold"><strong id="rejectItemName"></strong></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger btn-sm" id="confirmRejectBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Reject</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<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.bootstrap4.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.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.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>
// Live Date and Time
function updateDateTime() {
    const now = new Date();
    const dateOptions = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
    const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };

    document.getElementById('currentDate').textContent = now.toLocaleDateString('en-US', dateOptions);
    document.getElementById('currentTime').textContent = now.toLocaleTimeString('en-US', timeOptions);
}
updateDateTime();
setInterval(updateDateTime, 1000);

$(document).ready(function() {
    // Initialize DataTable
    var table = $('#salesOrderTable').DataTable({
        dom: '<"row"<"col-sm-12 col-md-6"B><"col-sm-12 col-md-6"f>>rtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-sm' },
            { extend: 'csv', className: 'btn btn-sm' },
            { extend: 'excel', className: 'btn btn-sm' },
            { extend: 'pdf', className: 'btn btn-sm' },
            { extend: 'print', className: 'btn btn-sm' }
        ],
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, 'desc']],
        columnDefs: [
            { orderable: false, targets: [6] }
        ],
        language: {
            emptyTable: "No sales orders found"
        }
    });

    // Variables for modals
    var deleteId = null;
    var approveId = null;
    var rejectId = null;

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

    // Confirm delete
    $('#confirmDeleteBtn').on('click', function() {
        if (!deleteId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Deleting...');

        $.ajax({
            url: '{{ url("/superadmin/sales/order") }}/' + deleteId,
            type: 'DELETE',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(response) {
                $('#deleteModal').modal('hide');
                table.row('#row-' + deleteId).remove().draw(false);
                showToast('success', response.message || 'Sales Order deleted successfully!');
            },
            error: function(xhr) {
                showToast('error', xhr.responseJSON?.message || 'Failed to delete sales order.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Delete');
                deleteId = null;
            }
        });
    });

    // Approve button click
    $(document).on('click', '.approve-btn', function() {
        approveId = $(this).data('id');
        $('#approveItemName').text($(this).data('so'));
        $('#approveModal').modal('show');
    });

    // Confirm approve
    $('#confirmApproveBtn').on('click', function() {
        if (!approveId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Approving...');

        $.ajax({
            url: '{{ url("/superadmin/sales/order") }}/' + approveId + '/approve',
            type: 'POST',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(response) {
                $('#approveModal').modal('hide');
                showToast('success', response.message || 'Sales Order approved!');
                setTimeout(function() { location.reload(); }, 1000);
            },
            error: function(xhr) {
                showToast('error', xhr.responseJSON?.message || 'Failed to approve sales order.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Approve');
                approveId = null;
            }
        });
    });

    // Reject button click
    $(document).on('click', '.reject-btn', function() {
        rejectId = $(this).data('id');
        $('#rejectItemName').text($(this).data('so'));
        $('#rejectModal').modal('show');
    });

    // Confirm reject
    $('#confirmRejectBtn').on('click', function() {
        if (!rejectId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Rejecting...');

        $.ajax({
            url: '{{ url("/superadmin/sales/order") }}/' + rejectId + '/reject',
            type: 'POST',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(response) {
                $('#rejectModal').modal('hide');
                showToast('success', response.message || 'Sales Order rejected!');
                setTimeout(function() { location.reload(); }, 1000);
            },
            error: function(xhr) {
                showToast('error', xhr.responseJSON?.message || 'Failed to reject sales order.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Reject');
                rejectId = null;
            }
        });
    });

    // Toast notification helper
    function showToast(type, message) {
        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        var toastHtml = `
            <div class="toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 280px;">
                <div class="toast-body d-flex align-items-center p-3">
                    <i class="fas ${icon} mr-2"></i>
                    <span>${message}</span>
                    <button type="button" class="ml-auto close text-white" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }
});
</script>
@endsection
