@extends('layouts.app')

@push('style')
<!-- Toastr CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<style>
    /* Fix sidebar behavior */
    .sidebar-mini.sidebar-collapse .main-sidebar {
        width: 0;
    }
    
    .sidebar-mini:not(.sidebar-collapse) .main-sidebar {
        width: 250px;
    }
    
    /* Ensure sidebar stays fixed */
    .main-sidebar {
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        z-index: 1038;
        transition: all 0.3s ease;
    }
    
    /* Content wrapper adjustments */
    .content-wrapper {
        margin-left: 250px;
        transition: all 0.3s ease;
    }
    
    .sidebar-mini.sidebar-collapse .content-wrapper {
        margin-left: 0;
    }
    
    /* Mobile responsive fixes */
    @media (max-width: 991.98px) {
        .main-sidebar {
            margin-left: -250px;
        }
        
        .sidebar-open .main-sidebar {
            margin-left: 0;
        }
        
        .content-wrapper {
            margin-left: 0;
        }
        
        .sidebar-open .content-wrapper {
            transform: translateX(250px);
        }
    }
</style>
@endpush

@section('main')
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Sales History</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('sales.index') }}">Sales Management</a></li>
                        <li class="breadcrumb-item active">Sales History</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Simple Summary Cards -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3>{{ $sales->count() }}</h3>
                            <p>Total Sales</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3>BHD {{ number_format($sales->sum('total_amount'), 2) }}</h3>
                            <p>Total Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3>{{ $sales->where('payment_status', 'partial')->count() }}</h3>
                            <p>Partial Payments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3>{{ $sales->where('payment_status', 'unpaid')->count() }}</h3>
                            <p>Unpaid Sales</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-times-circle"></i>
                        </div>
                    </div>
                </div>
            </div>

                <!-- Dynamic Exchange Summary Row -->
                <div class="row">
                    <div class="col-lg-3 col-12">
                        <div class="small-box bg-gradient-primary">
                            <div class="inner">
                                @php
                                    $totalSaleAmount = $sales->sum('total_amount');
                                    $totalExchangeValue = $sales->sum('total_exchange_value');
                                    $totalActualCash = $totalSaleAmount - $totalExchangeValue;
                                @endphp
                                <h3 id="totalActualCash">BHD {{ number_format($totalActualCash, 2) }}</h3>
                                <p>Total Actual Cash</p>
                                <small class="text-light" id="totalActualCashBreakdown">
                                    <i class="fas fa-calculator"></i> 
                                    Sales: {{ number_format($totalSaleAmount, 2) }} - 
                                    Exchanges: {{ number_format($totalExchangeValue, 2) }}
                                </small>
                            </div>
                            <div class="icon">
                                <i class="fas fa-hand-holding-usd"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-12">
                        <div class="small-box bg-gradient-success">
                            <div class="inner">
                                <h3 id="salesWithExchanges">{{ $sales->where('has_exchanges', true)->count() }}</h3>
                                <p>Sales with Exchanges</p>
                                <small class="text-light" id="salesWithExchangesSubtext">Sales that included exchanges</small>
                            </div>
                            <div class="icon">
                                <i class="fas fa-exchange-alt"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-12">
                        <div class="small-box bg-gradient-info">
                            <div class="inner">
                                <h3 id="totalExchangeItems">{{ $sales->sum('exchange_count') }}</h3>
                                <p>Total Exchange Items</p>
                                <small class="text-light" id="totalExchangeItemsSubtext">Individual items exchanged</small>
                            </div>
                            <div class="icon">
                                <i class="fas fa-mobile-alt"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-12">
                        <div class="small-box bg-gradient-warning">
                            <div class="inner">
                                <h3 id="totalExchangeDiscount">BHD {{ number_format($sales->sum('total_exchange_value'), 2) }}</h3>
                                <p>Total Exchange Discount</p>
                                <small class="text-light" id="totalExchangeDiscountSubtext">
                                    <i class="fas fa-percent"></i> 
                                    {{ $totalSaleAmount > 0 ? number_format(($totalExchangeValue / $totalSaleAmount) * 100, 1) : 0 }}% of sales
                                </small>
                            </div>
                            <div class="icon">
                                <i class="fas fa-tags"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Sales History Table -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-table mr-1"></i>
                                    Sales History
                                </h3>
                                <div class="card-tools">
                                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                        <i class="fas fa-minus"></i>
                                    </button>
                                    <button type="button" class="btn btn-tool" data-card-widget="maximize">
                                        <i class="fas fa-expand"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <!-- Advanced Filters -->
                                <div class="row mb-4">
                                    <div class="col-12">
                                        <div class="card card-outline card-primary">
                                            <div class="card-header">
                                                <h3 class="card-title">
                                                    <i class="fas fa-filter mr-2"></i>Advanced Filters
                                                    <span class="badge badge-success badge-sm ml-2">
                                                        <i class="fas fa-bolt"></i> Auto-Apply
                                                    </span>
                                                </h3>
                                                <div class="card-tools">
                                                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                                        <i class="fas fa-minus"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <!-- Date Filter -->
                                                    <div class="col-lg-4 col-md-6 col-12 mb-3">
                                                        <label for="dateFilter" class="font-weight-bold">
                                                            <i class="fas fa-calendar-alt text-primary"></i> Date Filter
                                                        </label>
                                                        <select id="dateFilter" class="form-control">
                                                            <option value="all">All Dates</option>
                                                            <option value="today">Today</option>
                                                            <option value="yesterday">Yesterday</option>
                                                            <option value="last7">Last 7 Days</option>
                                                            <option value="last30">Last 30 Days</option>
                                                            <option value="last90">Last 90 Days</option>
                                                            <option value="last365">Last Year</option>
                                                            <option value="custom">Custom Date Range</option>
                                                        </select>
                                                    </div>

                                                    <!-- Custom Date Range -->
                                                    <div class="col-lg-4 col-md-6 col-12 mb-3" id="customDateRange" style="display: none;">
                                                        <label class="font-weight-bold">
                                                            <i class="fas fa-calendar-check text-success"></i> Custom Date Range
                                                        </label>
                                                        <div class="row">
                                                            <div class="col-6">
                                                                <input type="date" id="startDate" class="form-control" placeholder="Start Date">
                                                            </div>
                                                            <div class="col-6">
                                                                <input type="date" id="endDate" class="form-control" placeholder="End Date">
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- Sale Type Filter -->
                                                    <div class="col-lg-2 col-md-6 col-12 mb-3">
                                                        <label for="saleTypeFilter" class="font-weight-bold">
                                                            <i class="fas fa-tags text-info"></i> Sale Type
                                                        </label>
                                                        <select id="saleTypeFilter" class="form-control">
                                                            <option value="all">All Types</option>
                                                            <option value="regular_sale">Regular Sales</option>
                                                            <option value="direct_sale">Direct Sales</option>
                                                            <option value="with_exchange">With Exchange</option>
                                                        </select>
                                                    </div>

                                                    <!-- Payment Status Filter -->
                                                    <div class="col-lg-2 col-md-6 col-12 mb-3">
                                                        <label for="paymentStatusFilter" class="font-weight-bold">
                                                            <i class="fas fa-credit-card text-warning"></i> Payment Status
                                                        </label>
                                                        <select id="paymentStatusFilter" class="form-control">
                                                            <option value="all">All Status</option>
                                                            <option value="paid">Paid</option>
                                                            <option value="unpaid">Unpaid</option>
                                                            <option value="partial">Partial</option>
                                                        </select>
                                                    </div>
                                                </div>

                                                <div class="row">
                                                    <!-- Global Search -->
                                                    <div class="col-lg-6 col-md-8 col-12 mb-3">
                                                        <label for="globalSearch" class="font-weight-bold">
                                                            <i class="fas fa-search text-primary"></i> Global Search
                                                        </label>
                                                        <input type="text" id="globalSearch" class="form-control" placeholder="Search by customer name, sale ID, phone, etc...">
                                                    </div>

                                                    <!-- Filter Actions -->
                                                    <div class="col-lg-6 col-md-4 col-12 mb-3">
                                                        <label class="font-weight-bold">
                                                            <i class="fas fa-cogs text-secondary"></i> Actions
                                                        </label>
                                                        <div class="btn-group d-block">
                                                            <button type="button" id="clearFilters" class="btn btn-secondary">
                                                                <i class="fas fa-times"></i> Clear All
                                                            </button>
                                                            <button type="button" id="exportFiltered" class="btn btn-success">
                                                                <i class="fas fa-download"></i> Export
                                                            </button>
                                                            <button type="button" class="btn btn-info" data-toggle="tooltip" data-html="true" title="<b>Keyboard Shortcuts:</b><br>F - Focus Search<br>Ctrl+C - Clear Filters<br>Ctrl+E - Export<br>Ctrl+1 - Today Filter<br>Ctrl+7 - Last 7 Days<br><br><b>Auto-Filters:</b><br>All filters apply instantly when changed!">
                                                                <i class="fas fa-keyboard"></i> Help
                                                            </button>
                                                            <button type="button" id="testFilter" class="btn btn-warning" onclick="testDateFilter()">
                                                                <i class="fas fa-bug"></i> Test
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="table-responsive">
                                    <!-- Filter Summary -->
                                    <div id="filterSummary" class="alert alert-info" style="display: none;">
                                        <i class="fas fa-filter"></i>
                                        <strong>Active Filters:</strong>
                                        <span id="filterSummaryText"></span>
                                        <button type="button" class="close" onclick="$('#clearFilters').click();">
                                            <span>&times;</span>
                                        </button>
                                    </div>

                                    <table id="salesTable" class="table table-bordered table-striped table-hover">
                                        <thead class="thead-dark">
                                            <tr>
                                                <th><i class="fas fa-hashtag"></i> ID</th>
                                                <th><i class="fas fa-calendar"></i> Date</th>
                                                <th><i class="fas fa-user"></i> Customer</th>
                                                <th><i class="fas fa-boxes"></i> Items</th>
                                                <th><i class="fas fa-tag"></i> Brand/Model</th>
                                                <th><i class="fas fa-barcode"></i> IMEI/SN</th>
                                                <th><i class="fas fa-dollar-sign"></i> Actual Cash</th>
                                                <th><i class="fas fa-credit-card"></i> Payment Method</th>
                                                <th><i class="fas fa-check-circle"></i> Status</th>
                                                <th><i class="fas fa-cog"></i> Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($sales as $sale)
                                                <tr data-sale-id="{{ $sale->id }}"
                                                    data-sale-type="{{ $sale->type ?? 'regular_sale' }}"
                                                    data-transactions="{{ $sale->sellTransactions->toJson() }}"
                                                    data-exchanges="{{ $sale->exchanges->toJson() }}">
                                                    <td>
                                                        <strong>#{{ $sale->id }}</strong>
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                            <br><span class="badge badge-warning badge-sm">Direct Sale</span>
                                                        @else
                                                            <br><span class="badge badge-primary badge-sm">Regular Sale</span>
                                                            @if(isset($sale->has_exchanges) && $sale->has_exchanges)
                                                                <br><span class="badge badge-success badge-sm">
                                                                    <i class="fas fa-exchange-alt"></i> With Exchange
                                                                </span>
                                                            @endif
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-light">
                                                            {{ $sale->created_at->format('d M Y') }}
                                                        </span><br>
                                                        <small class="text-muted">{{ $sale->created_at->format('H:i A') }}</small>
                                                    </td>
                                                    <td>
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                            @if($sale->customer)
                                                                <strong>{{ $sale->customer->name }}</strong><br>
                                                                <small class="text-muted">{{ $sale->customer->phone ?? 'N/A' }}</small>
                                                            @else
                                                                <strong>{{ $sale->customer_name ?? 'Direct Customer' }}</strong><br>
                                                                <small class="text-muted">Direct Sale</small>
                                                            @endif
                                                        @else
                                                            @if($sale->customer)
                                                                <strong>{{ $sale->customer->name }}</strong><br>
                                                                <small class="text-muted">{{ $sale->customer->phone ?? 'N/A' }}</small>
                                                            @else
                                                                <span class="text-muted">Walk-in Customer</span>
                                                            @endif
                                                        @endif
                                                    </td>
                                                    <td>
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                            <span class="badge badge-warning">{{ $sale->quantity ?? 1 }} items</span>
                                                            <span class="text-muted">{{ $sale->product_type ?? 'Direct Product' }}</span>
                                                        @else
                                                            <span class="badge badge-info">{{ $sale->sellTransactions->count() }} items</span>
                                                            @if(isset($sale->has_exchanges) && $sale->has_exchanges)
                                                                <br><span class="badge badge-success badge-sm">
                                                                    <i class="fas fa-exchange-alt"></i> {{ $sale->exchange_count }} Exchange{{ $sale->exchange_count > 1 ? 's' : '' }}
                                                                </span>
                                                                <br><small class="text-success">Exchange Value: BHD {{ number_format($sale->total_exchange_value, 2) }}</small>
                                                            @endif
                                                        @endif
                                                        <button class="btn btn-xs btn-outline-primary ml-1 toggle-items" data-toggle="tooltip" title="View Items">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    </td>
                                                    <td>
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                            <!-- Direct Sale Brand/Model -->
                                                            @if(isset($sale->product_brand) && isset($sale->product_model))
                                                                <span class="badge badge-warning">{{ $sale->product_brand }}</span><br>
                                                                <small class="text-muted">{{ $sale->product_model }}</small>
                                                            @else
                                                                <span class="text-muted">Direct Sale</span><br>
                                                                <small class="text-muted">{{ $sale->product_type ?? 'Product' }}</small>
                                                            @endif
                                                        @else
                                                            <!-- Regular Sale Brand/Model -->
                                                            @php
                                                                $firstTransaction = $sale->sellTransactions->first();
                                                                $totalTransactions = $sale->sellTransactions->count();
                                                            @endphp
                                                            
                                                            @if($firstTransaction && $firstTransaction->product)
                                                                <span class="badge badge-info">{{ $firstTransaction->product->brand ?? 'N/A' }}</span><br>
                                                                <small class="text-muted">{{ $firstTransaction->product->model ?? 'N/A' }}</small>
                                                                @if($totalTransactions > 1)
                                                                    <br><small class="text-primary">+{{ $totalTransactions - 1 }} more</small>
                                                                @endif
                                                            @else
                                                                <span class="text-muted">No Product</span><br>
                                                                <small class="text-muted">Data</small>
                                                            @endif
                                                        @endif
                                                    </td>
                                                    <td>
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                            <!-- Direct Sale IMEI/SN -->
                                                            @if(isset($sale->imei_or_sn))
                                                                <code class="text-dark">{{ $sale->imei_or_sn }}</code>
                                                            @else
                                                                <span class="text-muted">N/A</span>
                                                            @endif
                                                        @else
                                                            <!-- Regular Sale IMEI/SN -->
                                                            @if($firstTransaction && $firstTransaction->product)
                                                                <code class="text-dark">{{ $firstTransaction->product->imei_or_sn ?? 'N/A' }}</code>
                                                                @if($totalTransactions > 1)
                                                                    <br><small class="text-primary">Multiple items</small>
                                                                @endif
                                                            @else
                                                                <span class="text-muted">N/A</span>
                                                            @endif
                                                        @endif
                                                    </td>
                                                    <td>
                                                        @php
                                                            $saleAmount = $sale->net_amount ?? $sale->total_amount;
                                                            $exchangeValue = $sale->total_exchange_value ?? 0;
                                                            $actualCash = $saleAmount - $exchangeValue;
                                                        @endphp
                                                        
                                                        <strong class="text-success">BHD {{ number_format($actualCash, 2) }}</strong>
                                                        <br><small class="text-muted">Actual Cash Received</small>
                                                        
                                                        @if($exchangeValue > 0)
                                                            <br><small class="text-info">
                                                                Sale: BHD {{ number_format($saleAmount, 2) }}
                                                            </small>
                                                            <br><small class="text-warning">
                                                                <i class="fas fa-minus-circle"></i> Exchange: BHD {{ number_format($exchangeValue, 2) }}
                                                            </small>
                                                        @endif
                                                        
                                                        @if(isset($sale->due_amount) && $sale->due_amount > 0)
                                                            <br><small class="text-danger">Due: BHD {{ number_format($sale->due_amount, 2) }}</small>
                                                        @endif
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale' && isset($sale->profit))
                                                            <br><small class="text-success">Profit: BHD {{ number_format($sale->profit, 2) }}</small>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-secondary">{{ ucfirst($sale->payment_method) }}</span>
                                                    </td>
                                                    <td>
                                                        @if ($sale->payment_status == 'paid')
                                                            <span class="badge badge-success"><i class="fas fa-check"></i> Paid</span>
                                                        @elseif($sale->payment_status == 'unpaid')
                                                            <span class="badge badge-danger"><i class="fas fa-times"></i> Unpaid</span>
                                                        @elseif($sale->payment_status == 'partial')
                                                            <span class="badge badge-warning"><i class="fas fa-clock"></i> Partial</span>
                                                        @else
                                                            <span class="badge badge-secondary">{{ ucfirst($sale->payment_status) }}</span>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <!-- Consolidated Action Buttons -->
                                                        <div class="btn-group" role="group">
                                                            <!-- Quick Actions (Most Used) -->
                                                            <button class="btn btn-sm btn-info toggle-items" 
                                                                    data-toggle="tooltip" 
                                                                    title="View Items" 
                                                                    data-placement="top">
                                                                <i class="fas fa-eye"></i>
                                                            </button>
                                                            
                                                            @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                                <!-- Direct Sale Actions -->
                                                                <a href="{{ route('direct-sales.invoice', str_replace('DS-', '', $sale->id)) }}" 
                                                                   target="_blank" 
                                                                   class="btn btn-sm btn-primary" 
                                                                   data-toggle="tooltip" 
                                                                   title="Print Direct Sale Receipt" 
                                                                   data-placement="top">
                                                                    <i class="fas fa-print"></i>
                                                                </a>
                                                            @else
                                                                <!-- Regular Sale Actions -->
                                                                <a href="{{ route('sales.table.invoice', $sale->id) }}" 
                                                                   target="_blank" 
                                                                   class="btn btn-sm btn-primary" 
                                                                   data-toggle="tooltip" 
                                                                   title="Print Receipt" 
                                                                   data-placement="top">
                                                                    <i class="fas fa-print"></i>
                                                                </a>
                                                                
                                                                @if($sale->payment_status != 'paid')
                                                                    <button class="btn btn-sm btn-success mark-paid" 
                                                                            data-sale-id="{{ $sale->id }}" 
                                                                            data-toggle="tooltip" 
                                                                            title="Mark as Paid" 
                                                                            data-placement="top">
                                                                        <i class="fas fa-check-circle"></i>
                                                                    </button>
                                                                @endif
                                                            @endif
                                                            
                                                            <!-- More Actions Dropdown -->
                                                            <div class="btn-group" role="group">
                                                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" 
                                                                        type="button" 
                                                                        data-toggle="dropdown" 
                                                                        aria-haspopup="true" 
                                                                        aria-expanded="false"
                                                                        data-toggle="tooltip" 
                                                                        title="More Actions">
                                                                    <i class="fas fa-ellipsis-v"></i>
                                                                </button>
                                                                <div class="dropdown-menu dropdown-menu-right">
                                                                    <h6 class="dropdown-header">
                                                                        <i class="fas fa-cog"></i> 
                                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                                            Direct Sale Actions
                                                                        @else
                                                                            Sale Actions
                                                                        @endif
                                                                    </h6>
                                                                    
                                                                    <button class="dropdown-item toggle-details" type="button">
                                                                        <i class="fas fa-info-circle text-info"></i> View Details
                                                                    </button>
                                                                    
                                                                    @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                                        <!-- Direct Sale Specific Actions -->
                                                                        <a class="dropdown-item" href="{{ route('direct-sales.invoice', str_replace('DS-', '', $sale->id)) }}" target="_blank">
                                                                            <i class="fas fa-file-invoice text-primary"></i> Full Invoice
                                                                        </a>
                                                                    @else
                                                                        <!-- Regular Sale Specific Actions -->
                                                                        <button class="dropdown-item quick-invoice" data-sale-id="{{ $sale->id }}" type="button">
                                                                            <i class="fas fa-receipt text-dark"></i> Quick Print
                                                                        </button>
                                                                        
                                                                        <a class="dropdown-item" href="{{ route('sales.table.invoice', $sale->id) }}" target="_blank">
                                                                            <i class="fas fa-file-invoice text-primary"></i> Full Invoice
                                                                        </a>
                                                                        
                                                                        @if($sale->payment_status != 'paid')
                                                                            <div class="dropdown-divider"></div>
                                                                            <h6 class="dropdown-header"><i class="fas fa-edit"></i> Modify</h6>
                                                                            
                                                                            <a class="dropdown-item" href="{{ route('sales.edit', $sale->id) }}">
                                                                                <i class="fas fa-edit text-warning"></i> Edit Sale
                                                                            </a>
                                                                        @endif
                                                                    @endif
                                                                    
                                                                    @if($sale->customer)
                                                                        <div class="dropdown-divider"></div>
                                                                        <a class="dropdown-item" href="{{ route('customers.show', $sale->customer->id) }}">
                                                                            <i class="fas fa-user text-info"></i> View Customer
                                                                        </a>
                                                                    @endif
                                                                    
                                                                    <div class="dropdown-divider"></div>
                                                                    <h6 class="dropdown-header text-danger"><i class="fas fa-exclamation-triangle"></i> Danger Zone</h6>
                                                                    @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                                        <button class="dropdown-item text-danger" onclick="confirmDirectSaleDelete('{{ str_replace('DS-', '', $sale->id) }}')" type="button">
                                                                            <i class="fas fa-trash"></i> Delete Direct Sale
                                                                        </button>
                                                                    @else
                                                                        <button class="dropdown-item text-danger" onclick="confirmDelete({{ $sale->id }})" type="button">
                                                                            <i class="fas fa-trash"></i> Delete Sale
                                                                        </button>
                                                                    @endif
                                                                </div>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Hidden forms for delete fallback -->
                                                        @if(isset($sale->type) && $sale->type == 'direct_sale')
                                                            <form id="delete-direct-form-{{ str_replace('DS-', '', $sale->id) }}" action="{{ route('direct-sales.destroy', str_replace('DS-', '', $sale->id)) }}" method="POST" style="display: none;">
                                                                @csrf
                                                                @method('DELETE')
                                                            </form>
                                                        @else
                                                            <form id="delete-form-{{ $sale->id }}" action="{{ route('sales.destroy', $sale->id) }}" method="POST" style="display: none;">
                                                                @csrf
                                                                @method('DELETE')
                                                            </form>
                                                        @endif
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                        <tfoot class="thead-light">
                                            <tr>
                                                <th colspan="6"><strong>Totals:</strong></th>
                                                <th><strong>BHD {{ number_format($sales->sum('total_amount'), 2) }}</strong></th>
                                                <th colspan="3"></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                            <!-- Pagination -->
                            <div class="card-footer clearfix">
                                {{ $sales->links() }}
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </section>

    <!-- Hidden iframe for printing -->
    <iframe id="printFrame" style="display: none;"></iframe>
@endsection

@push('script')
    <!-- Toastr JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script>
        // Toastr configuration
        toastr.options = {
            "closeButton": true,
            "debug": false,
            "newestOnTop": true,
            "progressBar": true,
            "positionClass": "toast-top-right",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "3000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };

        // GLOBAL DELETE FUNCTIONS - MOVED TO TOP FOR IMMEDIATE AVAILABILITY
        function confirmDelete(saleId) {
            console.log('Delete function called for sale ID:', saleId);
            
            if (confirm('⚠️ Are you sure you want to delete this sale?\n\nThis action cannot be undone and will remove:\n• Sale record\n• Associated transactions\n• Payment records\n• Exchange records\n\nClick OK to proceed or Cancel to abort.')) {
                console.log('User confirmed deletion');
                
                // Show loading state
                var deleteBtn = $('[onclick="confirmDelete(' + saleId + ')"]');
                if (deleteBtn.length > 0) {
                    var originalText = deleteBtn.html();
                    deleteBtn.html('<i class="fas fa-spinner fa-spin"></i> Deleting...');
                    deleteBtn.prop('disabled', true);
                }
                
                // Get CSRF token
                var csrfToken = $('meta[name="csrf-token"]').attr('content');
                
                // Try AJAX first, fallback to form submission
                if (typeof $ !== 'undefined') {
                    $.ajax({
                        url: '/sales/' + saleId,
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken,
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        data: JSON.stringify({
                            _token: csrfToken
                        }),
                        success: function(response) {
                            console.log('Delete response:', response);
                            if (response.success) {
                                // Show enhanced delete notification with sound
                                if (typeof notificationSystem !== 'undefined') {
                                    notificationSystem.delete('Sale Deleted!', 'Sale record has been permanently removed');
                                } else {
                                    alert('✅ Sale deleted successfully');
                                }
                                setTimeout(() => location.reload(), 1500);
                            } else {
                                if (typeof notificationSystem !== 'undefined') {
                                    notificationSystem.showError(response.message || 'Failed to delete sale', 'Delete Failed');
                                } else {
                                    alert('❌ Error: ' + response.message);
                                }
                                if (deleteBtn.length > 0) {
                                    deleteBtn.html(originalText);
                                    deleteBtn.prop('disabled', false);
                                }
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log('AJAX Delete failed, trying form submission fallback');
                            document.getElementById('delete-form-' + saleId).submit();
                        }
                    });
                } else {
                    document.getElementById('delete-form-' + saleId).submit();
                }
            } else {
                console.log('User cancelled deletion');
            }
        }

        function confirmDirectSaleDelete(directSaleId) {
            console.log('Direct sale delete function called for ID:', directSaleId);
            
            if (confirm('⚠️ Are you sure you want to delete this direct sale?\n\nThis action cannot be undone and will remove:\n• Direct sale record\n• All associated data\n\nClick OK to proceed or Cancel to abort.')) {
                console.log('User confirmed direct sale deletion');
                
                // Show loading state
                var deleteBtn = $('[onclick="confirmDirectSaleDelete(\'' + directSaleId + '\')"]');
                if (deleteBtn.length > 0) {
                    var originalText = deleteBtn.html();
                    deleteBtn.html('<i class="fas fa-spinner fa-spin"></i> Deleting...');
                    deleteBtn.prop('disabled', true);
                }
                
                // Get CSRF token
                var csrfToken = $('meta[name="csrf-token"]').attr('content');
                
                // Try AJAX first, fallback to form submission
                if (typeof $ !== 'undefined') {
                    $.ajax({
                        url: '/direct-sales/' + directSaleId,
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken,
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        data: JSON.stringify({
                            _token: csrfToken
                        }),
                        success: function(response) {
                            console.log('Direct sale delete response:', response);
                            if (response.success) {
                                // Show enhanced delete notification with sound
                                if (typeof notificationSystem !== 'undefined') {
                                    notificationSystem.delete('Direct Sale Deleted!', 'Direct sale record has been permanently removed');
                                } else {
                                    alert('✅ Direct sale deleted successfully');
                                }
                                setTimeout(() => location.reload(), 1500);
                            } else {
                                if (typeof notificationSystem !== 'undefined') {
                                    notificationSystem.showError(response.message || 'Failed to delete direct sale', 'Delete Failed');
                                } else {
                                    alert('❌ Error: ' + (response.message || 'Failed to delete direct sale'));
                                }
                                if (deleteBtn.length > 0) {
                                    deleteBtn.html(originalText);
                                    deleteBtn.prop('disabled', false);
                                }
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log('AJAX Direct sale delete failed, trying form submission fallback');
                            document.getElementById('delete-direct-form-' + directSaleId).submit();
                        }
                    });
                } else {
                    document.getElementById('delete-direct-form-' + directSaleId).submit();
                }
            } else {
                console.log('User cancelled direct sale deletion');
            }
        }

        $(document).ready(function() {
            // Fix sidebar behavior on page load
            $('body').removeClass('sidebar-open sidebar-collapse');
            $('body').addClass('sidebar-mini layout-fixed');
            
            // Ensure sidebar toggle works properly
            $('[data-widget="pushmenu"]').on('click', function(e) {
                e.preventDefault();
                if ($('body').hasClass('sidebar-collapse')) {
                    $('body').removeClass('sidebar-collapse');
                } else {
                    $('body').addClass('sidebar-collapse');
                }
            });
            
            // Fix for mobile sidebar
            if ($(window).width() <= 991) {
                $('body').addClass('sidebar-collapse');
            }
            
            // Handle window resize
            $(window).on('resize', function() {
                if ($(window).width() <= 991) {
                    $('body').addClass('sidebar-collapse');
                } else {
                    $('body').removeClass('sidebar-collapse');
                }
            });
            
            // Initialize tooltips
            $('[data-toggle="tooltip"]').tooltip();

            // Initialize DataTables with enhanced features
            var salesTable = $('#salesTable').DataTable({
                "paging": true,
                "lengthChange": true,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                "order": [[1, "desc"]], // Sort by date column descending
                "columnDefs": [
                    { "orderable": false, "targets": [9] }, // Disable sorting for actions column
                    { "className": "text-center", "targets": [0, 3, 4, 5, 8, 9] }, // Center align specific columns
                    { "width": "8%", "targets": [4, 5] }, // Set width for brand/model and IMEI columns
                    { "width": "15%", "targets": [6] } // Set width for actual cash column
                ],
                "language": {
                    "search": "Quick Search:",
                    "searchPlaceholder": "Search sales...",
                    "lengthMenu": "Show _MENU_ sales per page",
                    "info": "Showing _START_ to _END_ of _TOTAL_ sales",
                    "infoEmpty": "No sales found",
                    "infoFiltered": "(filtered from _MAX_ total sales)",
                    "zeroRecords": "No matching sales found",
                    "paginate": {
                        "first": "First",
                        "last": "Last", 
                        "next": "Next",
                        "previous": "Previous"
                    }
                },
                "dom": 'Bfrtip',
                "buttons": [
                    {
                        extend: 'copy',
                        text: '<i class="fas fa-copy"></i> Copy',
                        className: 'btn btn-secondary btn-sm'
                    },
                    {
                        extend: 'csv',
                        text: '<i class="fas fa-file-csv"></i> CSV',
                        className: 'btn btn-success btn-sm'
                    },
                    {
                        extend: 'excel',
                        text: '<i class="fas fa-file-excel"></i> Excel',
                        className: 'btn btn-success btn-sm'
                    },
                    {
                        extend: 'pdf',
                        text: '<i class="fas fa-file-pdf"></i> PDF',
                        className: 'btn btn-danger btn-sm'
                    },
                    {
                        extend: 'print',
                        text: '<i class="fas fa-print"></i> Print',
                        className: 'btn btn-info btn-sm'
                    }
                ],
                "initComplete": function() {
                    // Custom styling for DataTable elements
                    $('.dt-buttons').addClass('mb-2');
                    $('.dataTables_filter input').addClass('form-control-sm').attr('placeholder', 'Quick search...');
                }
            });

            // Advanced Filter Functionality with improved DataTables integration
            
            // Show/hide custom date range and apply filter automatically
            $('#dateFilter').on('change', function() {
                if ($(this).val() === 'custom') {
                    $('#customDateRange').slideDown();
                } else {
                    $('#customDateRange').slideUp();
                    applyAdvancedFilters(); // Apply filter automatically
                }
            });

            // Auto-apply filters when date inputs change
            $('#startDate, #endDate').on('change', function() {
                if ($('#dateFilter').val() === 'custom' && $('#startDate').val() && $('#endDate').val()) {
                    applyAdvancedFilters();
                }
            });

            // Auto-apply filters when sale type changes
            $('#saleTypeFilter').on('change', function() {
                applyAdvancedFilters();
            });

            // Auto-apply filters when payment status changes
            $('#paymentStatusFilter').on('change', function() {
                applyAdvancedFilters();
            });

            // Global search functionality - real-time
            $('#globalSearch').on('keyup', function() {
                salesTable.search(this.value).draw();
            });

            // Remove apply filters button functionality
            // $('#applyFilters').on('click', function() {
            //     applyAdvancedFilters();
            // });

            // Clear all filters
            $('#clearFilters').on('click', function() {
                $('#dateFilter').val('all');
                $('#saleTypeFilter').val('all');
                $('#paymentStatusFilter').val('all');
                $('#globalSearch').val('');
                $('#startDate').val('');
                $('#endDate').val('');
                $('#customDateRange').hide();
                
                // Remove visual feedback classes
                $('#dateFilter, #saleTypeFilter, #paymentStatusFilter').removeClass('filter-applied');
                
                // Clear all DataTable filters
                salesTable.search('').columns().search('').draw();
                
                // Update summary cards to show all data
                updateSummaryCards();
                
                // Hide filter summary
                $('#filterSummary').slideUp();
                
                // Show success message
                toastr.success('All filters cleared - showing all sales!');
            });

            // Export filtered data
            $('#exportFiltered').on('click', function() {
                // Get current filtered data
                var filteredData = salesTable.rows({ filter: 'applied' }).data();
                
                if (filteredData.length === 0) {
                    toastr.warning('No data to export. Please adjust your filters.');
                    return;
                }
                
                // Trigger Excel export with filtered data
                salesTable.button('.buttons-excel').trigger();
                toastr.success('Exporting ' + filteredData.length + ' sales records...');
            });

            // Advanced filter function with improved logic and summary updates
            function applyAdvancedFilters() {
                var dateFilter = $('#dateFilter').val();
                var saleTypeFilter = $('#saleTypeFilter').val();
                var paymentStatusFilter = $('#paymentStatusFilter').val();
                var startDate = $('#startDate').val();
                var endDate = $('#endDate').val();

                console.log('Applying filters:', {dateFilter, saleTypeFilter, paymentStatusFilter});

                // Clear all existing column searches
                salesTable.columns().search('').draw(false);

                // Apply custom filter function
                $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
                    // data[0] = ID column, data[1] = Date column, data[8] = Status column (was data[6])
                    var rowDate = data[1]; // Date column content
                    var rowType = data[0];  // ID column (contains type badges)
                    var rowStatus = data[8]; // Status column (now column 8 instead of 6)
                    
                    // Date filtering
                    if (dateFilter !== 'all') {
                        var matchDate = false;
                        var today = new Date();
                        
                        switch(dateFilter) {
                            case 'today':
                                var todayStr = formatDateForSearch(today);
                                matchDate = rowDate.includes(todayStr);
                                console.log('Today filter check:', todayStr, 'vs', rowDate, '=', matchDate);
                                break;
                                
                            case 'yesterday':
                                var yesterday = new Date(today);
                                yesterday.setDate(yesterday.getDate() - 1);
                                var yesterdayStr = formatDateForSearch(yesterday);
                                matchDate = rowDate.includes(yesterdayStr);
                                console.log('Yesterday filter check:', yesterdayStr, 'vs', rowDate, '=', matchDate);
                                break;
                                
                            case 'last7':
                                var last7 = new Date(today);
                                last7.setDate(last7.getDate() - 7);
                                matchDate = isDateInRange(rowDate, last7, today);
                                break;
                                
                            case 'last30':
                                var last30 = new Date(today);
                                last30.setDate(last30.getDate() - 30);
                                matchDate = isDateInRange(rowDate, last30, today);
                                break;
                                
                            case 'custom':
                                if (startDate && endDate) {
                                    matchDate = isDateInRange(rowDate, new Date(startDate), new Date(endDate));
                                } else {
                                    matchDate = true; // If no custom range set, show all
                                }
                                break;
                                
                            default:
                                matchDate = true;
                        }
                        
                        if (!matchDate) return false;
                    }
                    
                    // Sale type filtering
                    if (saleTypeFilter !== 'all') {
                        var matchType = false;
                        switch(saleTypeFilter) {
                            case 'regular_sale':
                                matchType = rowType.includes('Regular Sale');
                                break;
                            case 'direct_sale':
                                matchType = rowType.includes('Direct Sale');
                                break;
                            case 'with_exchange':
                                matchType = rowType.includes('With Exchange');
                                break;
                        }
                        if (!matchType) return false;
                    }
                    
                    // Payment status filtering
                    if (paymentStatusFilter !== 'all') {
                        var matchStatus = rowStatus.toLowerCase().includes(paymentStatusFilter.toLowerCase());
                        if (!matchStatus) return false;
                    }
                    
                    return true; // Show this row
                });

                // Redraw table with new filters
                salesTable.draw();
                
                // Update summary cards based on filtered data
                updateSummaryCards();
                
                // Remove the custom filter to avoid conflicts
                $.fn.dataTable.ext.search.pop();

                // Update UI feedback
                updateFilterFeedback(dateFilter, saleTypeFilter, paymentStatusFilter);
            }

            // Function to update summary cards based on filtered table data
            function updateSummaryCards() {
                // Add loading animation
                $('.small-box').addClass('updating');
                
                // Get filtered rows from DataTable
                var filteredRows = salesTable.rows({ filter: 'applied' }).nodes();
                
                var totalSales = 0;
                var totalSaleAmount = 0;
                var totalExchangeValue = 0;
                var partialSaleAmount = 0;
                var partialExchangeValue = 0;
                var unpaidAmount = 0;
                var salesWithExchanges = 0;
                var totalExchangeItems = 0;
                
                console.log('Updating summary cards for', filteredRows.length, 'filtered rows');
                
                // Parse each filtered row for calculations
                $(filteredRows).each(function() {
                    var row = $(this);
                    totalSales++;
                    
                    // Extract actual cash amount from the Actual Cash column (column 7, was column 5)
                    var actualCashCell = row.find('td:nth-child(7)');
                    var actualCashAmount = 0;
                    var saleAmount = 0;
                    var exchangeAmount = 0;
                    
                    // Try to extract the main cash amount (the big number)
                    var mainAmountMatch = actualCashCell.text().match(/BHD ([\d,]+\.?\d*)/);
                    if (mainAmountMatch) {
                        actualCashAmount = parseFloat(mainAmountMatch[1].replace(/,/g, ''));
                    }
                    
                    // Extract breakdown amounts if available
                    var saleAmountMatch = actualCashCell.text().match(/Sale: BHD ([\d,]+\.?\d*)/);
                    var exchangeAmountMatch = actualCashCell.text().match(/Exchange: BHD ([\d,]+\.?\d*)/);
                    
                    if (saleAmountMatch) {
                        saleAmount = parseFloat(saleAmountMatch[1].replace(/,/g, ''));
                    } else {
                        // If no breakdown, assume the actual cash is the sale amount
                        saleAmount = actualCashAmount;
                    }
                    
                    if (exchangeAmountMatch) {
                        exchangeAmount = parseFloat(exchangeAmountMatch[1].replace(/,/g, ''));
                    }
                    
                    // Check payment status (column 9, was column 7)
                    var statusText = row.find('td:nth-child(9)').text().toLowerCase();
                    
                    if (statusText.includes('paid')) {
                        totalSaleAmount += saleAmount;
                        totalExchangeValue += exchangeAmount;
                    } else if (statusText.includes('partial')) {
                        partialSaleAmount += saleAmount;
                        partialExchangeValue += exchangeAmount;
                    } else if (statusText.includes('unpaid')) {
                        unpaidAmount += saleAmount;
                    }
                    
                    // Check for exchanges
                    var itemsText = row.find('td:nth-child(4)').text();
                    if (itemsText.includes('Exchange')) {
                        salesWithExchanges++;
                        var exchangeCountMatch = itemsText.match(/(\d+) Exchange/);
                        if (exchangeCountMatch) {
                            totalExchangeItems += parseInt(exchangeCountMatch[1]);
                        } else {
                            totalExchangeItems += 1; // Default to 1 if no count found
                        }
                    }
                });
                
                // Calculate actual cash amounts
                var actualCashReceived = totalSaleAmount - totalExchangeValue;
                var partialCashReceived = partialSaleAmount - partialExchangeValue;
                var totalActualCash = actualCashReceived + partialCashReceived;
                
                console.log('Summary calculations:', {
                    totalSales,
                    actualCashReceived,
                    partialCashReceived,
                    unpaidAmount,
                    totalActualCash,
                    salesWithExchanges,
                    totalExchangeItems
                });
                
                // Animate updates
                setTimeout(function() {
                    // Update the summary cards
                    $('#totalSalesCount').text(totalSales);
                    $('#actualCashReceived').text('BHD ' + actualCashReceived.toFixed(2));
                    $('#partialCashReceived').text('BHD ' + partialCashReceived.toFixed(2));
                    $('#unpaidSales').text('BHD ' + unpaidAmount.toFixed(2));
                    $('#totalActualCash').text('BHD ' + totalActualCash.toFixed(2));
                    $('#salesWithExchanges').text(salesWithExchanges);
                    $('#totalExchangeItems').text(totalExchangeItems);
                    $('#totalExchangeDiscount').text('BHD ' + (totalExchangeValue + partialExchangeValue).toFixed(2));
                    
                    // Update breakdown texts
                    $('#actualCashBreakdown').text(
                        'Sales: BHD ' + totalSaleAmount.toFixed(2) + ' - Exchanges: BHD ' + totalExchangeValue.toFixed(2)
                    );
                    $('#partialCashBreakdown').text(
                        'Sales: BHD ' + partialSaleAmount.toFixed(2) + ' - Exchanges: BHD ' + partialExchangeValue.toFixed(2)
                    );
                    $('#totalActualCashBreakdown').html(
                        '<i class="fas fa-calculator"></i> Sales: ' + (totalSaleAmount + partialSaleAmount).toFixed(2) + 
                        ' - Exchanges: ' + (totalExchangeValue + partialExchangeValue).toFixed(2)
                    );
                    
                    // Update percentage
                    var totalAmount = totalSaleAmount + partialSaleAmount + unpaidAmount;
                    var totalExchanges = totalExchangeValue + partialExchangeValue;
                    var exchangePercentage = totalAmount > 0 ? ((totalExchanges / totalAmount) * 100) : 0;
                    
                    $('#totalExchangeDiscountSubtext').html(
                        '<i class="fas fa-percent"></i> ' + exchangePercentage.toFixed(1) + '% of sales'
                    );
                    
                    // Update subtexts based on current filter
                    var dateFilter = $('#dateFilter').val();
                    var filterText = 'All time';
                    
                    switch(dateFilter) {
                        case 'today':
                            filterText = 'Today only';
                            break;
                        case 'yesterday':
                            filterText = 'Yesterday only';
                            break;
                        case 'last7':
                            filterText = 'Last 7 days';
                            break;
                        case 'last30':
                            filterText = 'Last 30 days';
                            break;
                        case 'custom':
                            filterText = 'Custom date range';
                            break;
                    }
                    
                    $('#totalSalesSubtext').text(filterText);
                    $('#unpaidSalesSubtext').text('Outstanding (' + filterText + ')');
                    $('#salesWithExchangesSubtext').text('With exchanges (' + filterText + ')');
                    $('#totalExchangeItemsSubtext').text('Items exchanged (' + filterText + ')');
                    
                    // Remove loading animation
                    $('.small-box').removeClass('updating');
                    
                    // Add success feedback
                    toastr.info('Summary updated for ' + totalSales + ' sales', 'Cards Updated');
                }, 300);
            }

            // Helper function to check if a date string is in range
            function isDateInRange(dateStr, startDate, endDate) {
                // Extract date from the cell content (format: "20 Oct 2025")
                var dateParts = dateStr.match(/(\d{1,2})\s(\w{3})\s(\d{4})/);
                if (!dateParts) return false;
                
                var months = {'Jan':0,'Feb':1,'Mar':2,'Apr':3,'May':4,'Jun':5,
                             'Jul':6,'Aug':7,'Sep':8,'Oct':9,'Nov':10,'Dec':11};
                
                var cellDate = new Date(
                    parseInt(dateParts[3]), // year
                    months[dateParts[2]], // month
                    parseInt(dateParts[1]) // day
                );
                
                return cellDate >= startDate && cellDate <= endDate;
            }

            // Helper function to update filter feedback
            function updateFilterFeedback(dateFilter, saleTypeFilter, paymentStatusFilter) {
                // Visual feedback - add active filter classes
                $('#dateFilter, #saleTypeFilter, #paymentStatusFilter').removeClass('filter-applied');
                
                if (dateFilter !== 'all') $('#dateFilter').addClass('filter-applied');
                if (saleTypeFilter !== 'all') $('#saleTypeFilter').addClass('filter-applied');
                if (paymentStatusFilter !== 'all') $('#paymentStatusFilter').addClass('filter-applied');

                // Show filter applied message and summary
                var activeFilters = [];
                var filterDetails = [];
                
                if (dateFilter !== 'all') {
                    activeFilters.push('Date');
                    var dateText = dateFilter.charAt(0).toUpperCase() + dateFilter.slice(1);
                    if (dateFilter === 'custom' && $('#startDate').val() && $('#endDate').val()) {
                        dateText = `${$('#startDate').val()} to ${$('#endDate').val()}`;
                    }
                    filterDetails.push(`Date: ${dateText}`);
                }
                if (saleTypeFilter !== 'all') {
                    activeFilters.push('Sale Type');
                    filterDetails.push(`Type: ${saleTypeFilter.replace('_', ' ')}`);
                }
                if (paymentStatusFilter !== 'all') {
                    activeFilters.push('Payment Status');
                    filterDetails.push(`Status: ${paymentStatusFilter}`);
                }
                
                if (activeFilters.length > 0) {
                    $('#filterSummaryText').text(filterDetails.join(' | '));
                    $('#filterSummary').slideDown();
                    toastr.success('Filter applied: ' + activeFilters.join(', '));
                } else {
                    $('#filterSummary').slideUp();
                }
            }

            // Helper function to format date for search (matches table format: "20 Oct 2025")
            function formatDateForSearch(date) {
                var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                var day = date.getDate(); // Don't pad with zero for single digits
                var month = months[date.getMonth()];
                var year = date.getFullYear();
                return day + ' ' + month + ' ' + year;
            }

            // Helper function to create date range regex with proper formatting
            function getDateRangeRegexFormatted(startDate, endDate) {
                var dates = [];
                var currentDate = new Date(startDate);
                
                while (currentDate <= endDate) {
                    dates.push(formatDateForSearch(currentDate));
                    currentDate.setDate(currentDate.getDate() + 1);
                }
                
                return dates.join('|');
            }

            // Legacy function for backward compatibility
            function getDateRangeRegex(startDate, endDate) {
                return getDateRangeRegexFormatted(startDate, endDate);
            }

            // Test function to debug filtering
            function testDateFilter() {
                console.log('=== FILTER DEBUG TEST ===');
                var today = new Date();
                var todayFormatted = formatDateForSearch(today);
                console.log('Today formatted:', todayFormatted);
                
                // Get all date data from table
                var dateData = salesTable.column(1).data().toArray();
                console.log('All dates in table:', dateData);
                
                // Test if any dates match today
                var matches = dateData.filter(date => date.includes(todayFormatted));
                console.log('Dates matching today:', matches);
                
                alert('Check console for debug info. Today formatted: ' + todayFormatted);
            }

            // Keyboard shortcuts for power users
            $(document).on('keydown', function(e) {
                // Only trigger if not typing in an input field
                if (!$(e.target).is('input, textarea, select')) {
                    switch(e.which) {
                        case 70: // F key - Focus search
                            e.preventDefault();
                            $('#globalSearch').focus();
                            break;
                        case 67: // C key - Clear filters
                            if (e.ctrlKey || e.metaKey) {
                                e.preventDefault();
                                $('#clearFilters').click();
                            }
                            break;
                        case 69: // E key - Export
                            if (e.ctrlKey || e.metaKey) {
                                e.preventDefault();
                                $('#exportFiltered').click();
                            }
                            break;
                        case 49: // 1 key - Today filter
                            if (e.ctrlKey || e.metaKey) {
                                e.preventDefault();
                                $('#dateFilter').val('today').trigger('change');
                            }
                            break;
                        case 55: // 7 key - Last 7 days
                            if (e.ctrlKey || e.metaKey) {
                                e.preventDefault();
                                $('#dateFilter').val('last7').trigger('change');
                            }
                            break;
                    }
                }
            });

            // No need for Enter key to apply filters since they auto-apply
            // $('#globalSearch, #startDate, #endDate').on('keypress', function(e) {
            //     if (e.which === 13) { // Enter key
            //         $('#applyFilters').click();
            //     }
            // });

            // Consolidated Action Button Handlers using Event Delegation

            // Toggle Items - View sale items with AJAX (handles both regular and direct sales)
            $(document).on('click', '.toggle-items', function() {
                var button = $(this);
                var row = button.closest('tr');
                var saleId = row.data('sale-id');
                var saleType = row.data('sale-type') || 'regular_sale';
                var icon = button.find('i');
                
                // Check if details row already exists
                var existingRow = $('#items-row-' + saleId);
                if (existingRow.length > 0) {
                    existingRow.remove();
                    icon.removeClass('fa-times').addClass('fa-eye');
                    button.attr('title', 'View Items').tooltip('dispose').tooltip();
                    return;
                }

                button.prop('disabled', true);
                icon.removeClass('fa-eye').addClass('fa-spinner fa-spin');

                if (saleType === 'direct_sale') {
                    // Handle direct sales differently - get data from row
                    var transactions = row.data('transactions');
                    var html = '<tr id="items-row-' + saleId + '" class="bg-warning text-dark border-left-warning"><td colspan="10">';
                    html += '<div class="p-4">';
                    html += '<h6 class="text-warning"><i class="fas fa-boxes mr-2"></i>Direct Sale Items #' + saleId + '</h6>';
                    
                    if (transactions && transactions.length > 0) {
                        html += '<div class="table-responsive">';
                        html += '<table class="table table-sm table-bordered table-hover">';
                        html += '<thead class="thead-light">';
                        html += '<tr><th>Product Type</th><th>Quantity</th><th>Unit Price</th><th>Total</th><th>Cost Price</th><th>Profit</th></tr>';
                        html += '</thead><tbody>';

                        transactions.forEach(function(transaction) {
                            var profit = (transaction.sell_price - transaction.buy_price) * transaction.sold_quantity;
                            
                            html += '<tr>';
                            html += '<td><strong>' + (transaction.product_name || 'Direct Product') + '</strong></td>';
                            html += '<td><span class="badge badge-warning">' + transaction.sold_quantity + '</span></td>';
                            html += '<td>BHD ' + parseFloat(transaction.sell_price).toFixed(2) + '</td>';
                            html += '<td><strong class="text-success">BHD ' + (transaction.sell_price * transaction.sold_quantity).toFixed(2) + '</strong></td>';
                            html += '<td class="text-muted">BHD ' + parseFloat(transaction.buy_price).toFixed(2) + '</td>';
                            html += '<td><span class="text-success font-weight-bold">BHD ' + profit.toFixed(2) + '</span></td>';
                            html += '</tr>';
                        });

                        html += '</tbody></table></div>';
                    } else {
                        html += '<div class="alert alert-warning mb-0"><i class="fas fa-info-circle mr-2"></i>No item details available for this direct sale</div>';
                    }
                    
                    html += '<button class="btn btn-sm btn-outline-warning mt-2" onclick="$(\'#items-row-' + saleId + '\').remove(); $(this).closest(\'tr\').prev().find(\'.toggle-items i\').removeClass(\'fa-times\').addClass(\'fa-eye\');">';
                    html += '<i class="fas fa-times mr-1"></i>Close</button>';
                    html += '</div></td></tr>';
                    
                    row.after(html);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-times');
                    button.attr('title', 'Close Items').tooltip('dispose').tooltip();
                    button.prop('disabled', false);
                } else {
                    // Handle regular sales with AJAX
                    var cleanSaleId = saleId.toString().replace('DS-', '');
                    
                    $.ajax({
                        url: '/sales/' + cleanSaleId + '/items',
                        method: 'GET',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            if (response.success) {
                                var transactions = response.transactions || [];
                                var exchanges = response.exchanges || [];
                                
                                var html = '<tr id="items-row-' + saleId + '" class="bg-light border-left-primary"><td colspan="10">';
                                html += '<div class="p-4">';
                                html += '<h6 class="text-primary"><i class="fas fa-boxes mr-2"></i>Items in Sale #' + saleId + '</h6>';
                                
                                if (transactions.length > 0) {
                                    html += '<div class="table-responsive">';
                                    html += '<table class="table table-sm table-bordered table-hover">';
                                    html += '<thead class="thead-light">';
                                    html += '<tr><th>Product</th><th>Brand</th><th>Model</th><th>IMEI/SN</th><th>Qty</th><th>Unit Price</th><th>Total</th><th>Profit</th></tr>';
                                    html += '</thead><tbody>';

                                    var totalProfit = 0;
                                    transactions.forEach(function(transaction) {
                                        var profit = (transaction.sell_price - transaction.buy_price) * transaction.sold_quantity;
                                        totalProfit += profit;
                                        
                                        html += '<tr>';
                                        html += '<td><strong>' + (transaction.product_name || 'N/A') + '</strong></td>';
                                        html += '<td><span class="badge badge-info">' + (transaction.brand || 'N/A') + '</span></td>';
                                        html += '<td>' + (transaction.model || 'N/A') + '</td>';
                                        html += '<td><code class="text-muted">' + (transaction.imei_or_sn || 'N/A') + '</code></td>';
                                        html += '<td><span class="badge badge-primary">' + transaction.sold_quantity + '</span></td>';
                                        html += '<td>BHD ' + parseFloat(transaction.sell_price).toFixed(2) + '</td>';
                                        html += '<td><strong class="text-success">BHD ' + (transaction.sell_price * transaction.sold_quantity).toFixed(2) + '</strong></td>';
                                        html += '<td><span class="text-success font-weight-bold">BHD ' + profit.toFixed(2) + '</span></td>';
                                        html += '</tr>';
                                    });

                                    html += '</tbody>';
                                    html += '<tfoot class="bg-light"><tr class="font-weight-bold">';
                                    html += '<td colspan="7" class="text-right">Total Profit:</td>';
                                    html += '<td class="text-success">BHD ' + totalProfit.toFixed(2) + '</td></tr></tfoot>';
                                    html += '</table></div>';
                                } else {
                                    html += '<div class="alert alert-info mb-0"><i class="fas fa-info-circle mr-2"></i>No items found for this sale</div>';
                                }
                                
                                // Add Exchange Information if exists
                                if (exchanges.length > 0) {
                                    html += '<hr>';
                                    html += '<h6 class="text-success"><i class="fas fa-exchange-alt mr-2"></i>Exchange Items</h6>';
                                    html += '<div class="table-responsive">';
                                    html += '<table class="table table-sm table-bordered table-hover bg-light-green">';
                                    html += '<thead class="thead-success">';
                                    html += '<tr><th>Brand</th><th>Model</th><th>IMEI</th><th>Exchange Value</th></tr>';
                                    html += '</thead><tbody>';

                                    var totalExchangeValue = 0;
                                    exchanges.forEach(function(exchange) {
                                        totalExchangeValue += parseFloat(exchange.price || 0);
                                        
                                        html += '<tr class="table-success">';
                                        html += '<td><span class="badge badge-success">' + (exchange.brand_name || exchange.custom_brand || 'N/A') + '</span></td>';
                                        html += '<td>' + (exchange.model_name || exchange.custom_model || 'N/A') + '</td>';
                                        html += '<td><code class="text-muted">' + (exchange.imei || 'N/A') + '</code></td>';
                                        html += '<td><strong class="text-success">BHD ' + parseFloat(exchange.price || 0).toFixed(2) + '</strong></td>';
                                        html += '</tr>';
                                    });

                                    html += '</tbody>';
                                    html += '<tfoot class="bg-success text-white"><tr class="font-weight-bold">';
                                    html += '<td colspan="3" class="text-right">Total Exchange Discount:</td>';
                                    html += '<td>BHD ' + totalExchangeValue.toFixed(2) + '</td></tr></tfoot>';
                                    html += '</table></div>';
                                }
                                
                                html += '<button class="btn btn-sm btn-outline-primary mt-2" onclick="$(\'#items-row-' + saleId + '\').remove(); $(this).closest(\'tr\').prev().find(\'.toggle-items i\').removeClass(\'fa-times\').addClass(\'fa-eye\');">';
                                html += '<i class="fas fa-times mr-1"></i>Close</button>';
                                html += '</div></td></tr>';
                                
                                row.after(html);
                                icon.removeClass('fa-spinner fa-spin').addClass('fa-times');
                                button.attr('title', 'Close Items').tooltip('dispose').tooltip();
                            } else {
                                alert('Failed to load sale items: ' + response.message);
                            }
                        },
                        error: function() {
                            alert('Failed to load sale items. Please try again.');
                        },
                        complete: function() {
                            button.prop('disabled', false);
                        }
                    });
                }
            });

            // Toggle-details functionality (View Sale Details)
            $('.toggle-details').on('click', function() {
                var button = $(this);
                var row = button.closest('tr');
                var saleId = row.data('sale-id');
                var icon = button.find('i');
                
                // Check if details row already exists
                var existingRow = $('#details-row-' + saleId);
                if (existingRow.length > 0) {
                    existingRow.remove();
                    icon.removeClass('fa-times').addClass('fa-eye');
                    return;
                }

                button.prop('disabled', true);
                icon.removeClass('fa-eye').addClass('fa-spinner fa-spin');

                // Load sale details via AJAX
                $.ajax({
                    url: '/sales/' + saleId + '/ajax-invoice',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        var html = '<tr id="details-row-' + saleId + '" class="bg-info"><td colspan="10">';
                        html += '<div class="p-3 text-white">';
                        html += '<h6><i class="fas fa-info-circle"></i> Sale Details #' + saleId + '</h6>';
                        html += '<div class="row">';
                        html += '<div class="col-md-6">';
                        html += '<strong>Customer:</strong> ' + (row.find('td:nth-child(3)').text().trim() || 'Walk-in Customer') + '<br>';
                        html += '<strong>Date:</strong> ' + row.find('td:nth-child(2) .badge').text() + '<br>';
                        html += '<strong>Time:</strong> ' + row.find('td:nth-child(2) small').text() + '<br>';
                        html += '</div>';
                        html += '<div class="col-md-6">';
                        html += '<strong>Total Amount:</strong> ' + row.find('td:nth-child(7) strong').text() + '<br>';
                        html += '<strong>Payment Method:</strong> ' + row.find('td:nth-child(8) .badge').text() + '<br>';
                        html += '<strong>Status:</strong> ' + row.find('td:nth-child(9) .badge').text() + '<br>';
                        html += '</div>';
                        html += '</div>';
                        html += '<div class="mt-3">';
                        html += '<button class="btn btn-light btn-sm" onclick="$(\'#details-row-' + saleId + '\').remove(); $(this).closest(\'tr\').prev().find(\'.toggle-details i\').removeClass(\'fa-times\').addClass(\'fa-eye\');">';
                        html += '<i class="fas fa-times"></i> Close Details</button>';
                        html += '</div>';
                        html += '</div></td></tr>';
                        
                        row.after(html);
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-times');
                    },
                    error: function() {
                        alert('Failed to load sale details. Please try again.');
                    },
                    complete: function() {
                        button.prop('disabled', false);
                    }
                });
            });

            // Enhanced Mark as Paid functionality with event delegation
            $(document).on('click', '.mark-paid', function() {
                var saleId = $(this).data('sale-id');
                var button = $(this);
                var originalHtml = button.html();
                
                if (confirm('✅ Mark this sale as paid?\n\nThis will update the payment status to "Paid" and set due amount to 0.')) {
                    button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
                    
                    $.ajax({
                        url: '/sales/' + saleId + '/mark-paid',
                        method: 'POST',
                        data: {
                            _token: $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            if (response.success) {
                                alert('✅ Sale marked as paid successfully!');
                                location.reload(); // Reload to update the status
                            } else {
                                alert('❌ Error: ' + response.message);
                                button.prop('disabled', false).html(originalHtml);
                            }
                        },
                        error: function() {
                            alert('❌ Error marking sale as paid. Please try again.');
                            button.prop('disabled', false).html(originalHtml);
                        }
                    });
                }
            });

            // Enhanced Quick Invoice functionality with event delegation
            $(document).on('click', '.quick-invoice', function() {
                var saleId = $(this).data('sale-id');
                var button = $(this);
                var originalHtml = button.html();
                
                button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
                
                $.ajax({
                    url: '/sales/' + saleId + '/ajax-invoice',
                    method: 'POST',
                    data: {
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(data) {
                        var iframe = document.getElementById('printFrame');
                        if (!iframe) {
                            // Create iframe if it doesn't exist
                            iframe = document.createElement('iframe');
                            iframe.id = 'printFrame';
                            iframe.style.display = 'none';
                            document.body.appendChild(iframe);
                        }
                        
                        var doc = iframe.contentWindow.document;
                        doc.open();
                        doc.write('<html><head><title>Invoice</title><style>body{font-family:Arial,sans-serif;}</style></head><body>' + data.html + '</body></html>');
                        doc.close();
                        
                        // Wait a bit for content to load then print
                        setTimeout(function() {
                            iframe.contentWindow.focus();
                            iframe.contentWindow.print();
                        }, 500);
                    },
                    error: function() {
                        alert('❌ Failed to load receipt. Please try again.');
                    },
                    complete: function() {
                        button.prop('disabled', false).html(originalHtml);
                    }
                });
            });

            // Toggle-details functionality with event delegation
            $(document).on('click', '.toggle-details', function() {
                var button = $(this);
                var row = button.closest('tr');
                var saleId = row.data('sale-id');
                var icon = button.find('i');
                
                // Check if details row already exists
                var existingRow = $('#details-row-' + saleId);
                if (existingRow.length > 0) {
                    existingRow.remove();
                    icon.removeClass('fa-times').addClass('fa-info-circle');
                    return;
                }

                button.prop('disabled', true);
                icon.removeClass('fa-info-circle').addClass('fa-spinner fa-spin');

                // Create sale details display
                var html = '<tr id="details-row-' + saleId + '" class="bg-info text-white"><td colspan="10">';
                html += '<div class="p-3">';
                html += '<h6><i class="fas fa-info-circle mr-2"></i>Sale Details #' + saleId + '</h6>';
                html += '<div class="row">';
                html += '<div class="col-md-6">';
                html += '<strong>Customer:</strong> ' + (row.find('td:nth-child(3)').text().trim() || 'Walk-in Customer') + '<br>';
                html += '<strong>Date:</strong> ' + row.find('td:nth-child(2) .badge').text() + '<br>';
                html += '<strong>Time:</strong> ' + row.find('td:nth-child(2) small').text() + '<br>';
                html += '</div>';
                html += '<div class="col-md-6">';
                html += '<strong>Total Amount:</strong> ' + row.find('td:nth-child(7) strong').text() + '<br>';
                html += '<strong>Payment Method:</strong> ' + row.find('td:nth-child(8) .badge').text() + '<br>';
                html += '<strong>Status:</strong> ' + row.find('td:nth-child(9) .badge').text() + '<br>';
                html += '</div>';
                html += '</div>';
                html += '<button class="btn btn-light btn-sm mt-2" onclick="$(\'#details-row-' + saleId + '\').remove(); $(this).closest(\'tr\').prev().find(\'.toggle-details i\').removeClass(\'fa-times\').addClass(\'fa-info-circle\');">';
                html += '<i class="fas fa-times mr-1"></i>Close Details</button>';
                html += '</div></td></tr>';
                
                row.after(html);
                icon.removeClass('fa-spinner fa-spin').addClass('fa-times');
                button.prop('disabled', false);
            });



            // Enhanced print receipt functionality
            $(document).on('click', '.print-receipt', function() {
                var saleId = $(this).data('sale-id');
                var button = $(this);
                var originalHtml = button.html();
                
                button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Loading...');
                
                $.post('/sales/' + saleId + '/ajax-invoice', {
                    _token: $('meta[name="csrf-token"]').attr('content')
                }, function(data) {
                    var iframe = document.getElementById('printFrame');
                    var doc = iframe.contentWindow.document;
                    doc.open();
                    doc.write('<html><head><title>Invoice</title></head><body>' + data.html + '</body></html>');
                    doc.close();
                    iframe.contentWindow.focus();
                    iframe.contentWindow.print();
                }).fail(function() {
                    alert('Failed to load receipt. Please try again.');
                }).always(function() {
                    button.prop('disabled', false).html(originalHtml);
                });
            });

            // Filter by payment status
            $('.filter-status').on('click', function() {
                var status = $(this).data('status');
                var table = $('#salesTable').DataTable();
                
                if (status === 'all') {
                    table.column(6).search('').draw();
                } else {
                    table.column(6).search(status).draw();
                }
                
                $('.filter-status').removeClass('active');
                $(this).addClass('active');
            });

            // Auto-refresh every 5 minutes
            setInterval(function() {
                if (confirm('Refresh sales data?')) {
                    location.reload();
                }
            }, 300000); // 5 minutes
        });

        // Global test function to debug filtering
        function testDateFilter() {
            console.log('=== FILTER DEBUG TEST ===');
            var today = new Date();
            var todayFormatted = formatDateForSearch(today);
            console.log('Today formatted:', todayFormatted);
            
            // Get all date data from table
            var salesTable = $('#salesTable').DataTable();
            var dateData = salesTable.column(1).data().toArray();
            console.log('All dates in table:', dateData);
            
            // Test if any dates match today
            var matches = dateData.filter(date => date.includes(todayFormatted));
            console.log('Dates matching today:', matches);
            
            alert('Check console for debug info. Today formatted: ' + todayFormatted);
        }

        // Helper function to format date for search (matches table format: "20 Oct 2025") - Global scope
        function formatDateForSearch(date) {
            var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            var day = date.getDate(); // Don't pad with zero for single digits
            var month = months[date.getMonth()];
            var year = date.getFullYear();
            return day + ' ' + month + ' ' + year;
        }

        }); // End document.ready

        // Debug: Make sure functions are available globally
        console.log('Delete functions loaded:', {
            confirmDelete: typeof confirmDelete,
            confirmDirectSaleDelete: typeof confirmDirectSaleDelete
        });
    </script>
@endpush
            console.log('Performing deletion for sale ID:', saleId);
            
            // Show loading state
            var deleteBtn = $('[onclick="confirmDelete(' + saleId + ')"]');
            var originalText = deleteBtn.html();
            deleteBtn.html('<i class="fas fa-spinner fa-spin"></i> Deleting...');
            deleteBtn.prop('disabled', true);
                
                // Get CSRF token
                var csrfToken = $('meta[name="csrf-token"]').attr('content');
                console.log('CSRF Token:', csrfToken);
                
                // Check if jQuery is available
                if (typeof $ === 'undefined') {
                    console.log('jQuery not available, using form submission');
                    document.getElementById('delete-form-' + saleId).submit();
                    return;
                }
                
                $.ajax({
                    url: '/sales/' + saleId,
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({
                        _token: csrfToken
                    }),
                    success: function(response) {
                        console.log('Delete response:', response);
                        if (response.success) {
                            // Show enhanced delete notification with sound
                            if (typeof notificationSystem !== 'undefined') {
                                notificationSystem.delete('Sale Deleted!', 'Sale record has been permanently removed');
                            } else {
                                alert('✅ Sale deleted successfully');
                            }
                            setTimeout(() => location.reload(), 1500); // Delay reload to show notification
                        } else {
                            if (typeof notificationSystem !== 'undefined') {
                                notificationSystem.showError(response.message || 'Failed to delete sale', 'Delete Failed');
                            } else {
                                alert('❌ Error: ' + response.message);
                            }
                            deleteBtn.html(originalText);
                            deleteBtn.prop('disabled', false);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log('AJAX Delete failed, trying form submission fallback');
                        console.log('Delete error:', xhr.responseText, status, error);
                        console.log('Status Code:', xhr.status);
                        
                        // Fallback to form submission
                        document.getElementById('delete-form-' + saleId).submit();
                    }
                });
        }


        
        // Debug: Make sure functions are available globally
        console.log('Delete functions loaded:', {
            confirmDelete: typeof confirmDelete,
            confirmDirectSaleDelete: typeof confirmDirectSaleDelete
        });
        
        }); // End document.ready
    </script>
@endpush
