

<?php $__env->startPush('style'); ?>
<!-- CSRF Token for AJAX requests -->
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<!-- 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>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('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="<?php echo e(route('dashboard')); ?>">Home</a></li>
                        <li class="breadcrumb-item"><a href="<?php echo e(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">
            <!-- Dynamic Summary Cards - Update with Filter -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3 id="filteredTotalSales"><?php echo e($sales->count()); ?></h3>
                            <p>Total Sales</p>
                            <small class="text-light">
                                <span id="filteredSalesStatus">All Records</span>
                            </small>
                        </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 id="filteredTotalRevenue"><?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($sales->sum('total_amount'), 2)); ?></h3>
                            <p>Total Revenue</p>
                            <small class="text-light">
                                <span id="filteredRevenueStatus">All Sales</span>
                            </small>
                        </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 id="filteredPartialPayments"><?php echo e($sales->where('payment_status', 'partial')->count()); ?></h3>
                            <p>Partial Payments</p>
                            <small class="text-light">
                                <span id="filteredPartialStatus">All Partials</span>
                            </small>
                        </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 id="filteredUnpaidSales"><?php echo e($sales->where('payment_status', 'unpaid')->count()); ?></h3>
                            <p>Unpaid Sales</p>
                            <small class="text-light">
                                <span id="filteredUnpaidStatus">All Unpaid</span>
                            </small>
                        </div>
                        <div class="icon">
                            <i class="fas fa-times-circle"></i>
                        </div>
                    </div>
                </div>
            </div>

                <!-- Dynamic Exchange Summary Row - Updates with Filters -->
                <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;
                                ?>
                                <h3 id="filteredActualCash"><?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($totalActualCash, 2)); ?></h3>
                                <p>Total Actual Cash</p>
                                <small class="text-light" id="filteredActualCashCalc">
                                    <i class="fas fa-calculator"></i> 
                                    Sales: <?php echo e(number_format($totalSaleAmount, 2)); ?> - 
                                    Exchanges: <?php echo e(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="filteredSalesWithExchanges"><?php echo e($sales->where('has_exchanges', true)->count()); ?></h3>
                                <p>Sales with Exchanges</p>
                                <small class="text-light" id="filteredExchangesSubtext">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="filteredTotalExchangeItems"><?php echo e($sales->sum('exchange_count')); ?></h3>
                                <p>Total Exchange Items</p>
                                <small class="text-light" id="filteredExchangeItemsSubtext">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="filteredTotalExchangeDiscount"><?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($sales->sum('total_exchange_value'), 2)); ?></h3>
                                <p>Total Exchange Discount</p>
                                <small class="text-light" id="filteredExchangeDiscountSubtext">
                                    <i class="fas fa-percent"></i> 
                                    <span id="filteredExchangePercentage"><?php echo e($totalSaleAmount > 0 ? number_format(($totalExchangeValue / $totalSaleAmount) * 100, 1) : 0); ?>%</span> 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>
                                                            <button type="button" class="btn btn-dark" onclick="debugFilters()">
                                                                <i class="fas fa-search"></i> Debug
                                                            </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>
                                            <?php $__currentLoopData = $sales; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sale): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <tr data-sale-id="<?php echo e($sale->id); ?>"
                                                    data-sale-type="<?php echo e($sale->type ?? 'regular_sale'); ?>"
                                                    data-transactions="<?php echo e($sale->sellTransactions->toJson()); ?>"
                                                    data-exchanges="<?php echo e($sale->exchanges->toJson()); ?>">
                                                    <td>
                                                        <strong>#<?php echo e($sale->id); ?></strong>
                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                            <br><span class="badge badge-warning badge-sm">Direct Sale</span>
                                                        <?php else: ?>
                                                            <br><span class="badge badge-primary badge-sm">Regular Sale</span>
                                                            <?php 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>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-light">
                                                            <?php echo e($sale->created_at->format('d M Y')); ?>

                                                        </span><br>
                                                        <small class="text-muted"><?php echo e($sale->created_at->format('H:i A')); ?></small>
                                                    </td>
                                                    <td>
                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                            <?php if($sale->customer): ?>
                                                                <strong><?php echo e($sale->customer->name); ?></strong><br>
                                                                <small class="text-muted"><?php echo e($sale->customer->phone ?? 'N/A'); ?></small>
                                                            <?php else: ?>
                                                                <strong><?php echo e($sale->customer_name ?? 'Direct Customer'); ?></strong><br>
                                                                <small class="text-muted">Direct Sale</small>
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                            <?php if($sale->customer): ?>
                                                                <strong><?php echo e($sale->customer->name); ?></strong><br>
                                                                <small class="text-muted"><?php echo e($sale->customer->phone ?? 'N/A'); ?></small>
                                                            <?php else: ?>
                                                                <span class="text-muted">Walk-in Customer</span>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                            <span class="badge badge-warning"><?php echo e($sale->quantity ?? 1); ?> items</span>
                                                            <span class="text-muted"><?php echo e($sale->product_type ?? 'Direct Product'); ?></span>
                                                        <?php else: ?>
                                                            <span class="badge badge-info"><?php echo e($sale->sellTransactions->count()); ?> items</span>
                                                            <?php if(isset($sale->has_exchanges) && $sale->has_exchanges): ?>
                                                                <br><span class="badge badge-success badge-sm">
                                                                    <i class="fas fa-exchange-alt"></i> <?php echo e($sale->exchange_count); ?> Exchange<?php echo e($sale->exchange_count > 1 ? 's' : ''); ?>

                                                                </span>
                                                                <br><small class="text-success">Exchange Value: <?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($sale->total_exchange_value, 2)); ?></small>
                                                            <?php endif; ?>
                                                        <?php 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>
                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                            <!-- Direct Sale Brand/Model -->
                                                            <?php if(isset($sale->product_brand) && isset($sale->product_model)): ?>
                                                                <span class="badge badge-warning"><?php echo e($sale->product_brand); ?></span><br>
                                                                <small class="text-muted"><?php echo e($sale->product_model); ?></small>
                                                            <?php else: ?>
                                                                <span class="text-muted">Direct Sale</span><br>
                                                                <small class="text-muted"><?php echo e($sale->product_type ?? 'Product'); ?></small>
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                            <!-- Regular Sale Brand/Model -->
                                                            <?php
                                                                $firstTransaction = $sale->sellTransactions->first();
                                                                $totalTransactions = $sale->sellTransactions->count();
                                                            ?>
                                                            
                                                            <?php if($firstTransaction && $firstTransaction->product): ?>
                                                                <span class="badge badge-info"><?php echo e($firstTransaction->product->ProductBrand->name ?? 'N/A'); ?></span><br>
                                                                <small class="text-muted"><?php echo e($firstTransaction->product->ProductModel->name ?? 'N/A'); ?></small>
                                                                <?php if($totalTransactions > 1): ?>
                                                                    <br><small class="text-primary">+<?php echo e($totalTransactions - 1); ?> more</small>
                                                                <?php endif; ?>
                                                            <?php else: ?>
                                                                <span class="text-muted">No Product</span><br>
                                                                <small class="text-muted">Data</small>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                            <!-- Direct Sale IMEI/SN -->
                                                            <?php if(isset($sale->imei_or_sn)): ?>
                                                                <code class="text-dark"><?php echo e($sale->imei_or_sn); ?></code>
                                                            <?php else: ?>
                                                                <span class="text-muted">N/A</span>
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                            <!-- Regular Sale IMEI/SN -->
                                                            <?php if($firstTransaction && $firstTransaction->product): ?>
                                                                <code class="text-dark"><?php echo e($firstTransaction->product->imei_or_sn ?? 'N/A'); ?></code>
                                                                <?php if($totalTransactions > 1): ?>
                                                                    <br><small class="text-primary">Multiple items</small>
                                                                <?php endif; ?>
                                                            <?php else: ?>
                                                                <span class="text-muted">N/A</span>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php
                                                            $saleAmount = $sale->net_amount ?? $sale->total_amount;
                                                            $exchangeValue = $sale->total_exchange_value ?? 0;
                                                            $actualCash = $saleAmount - $exchangeValue;
                                                        ?>
                                                        
                                                        <strong class="text-success"><?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($actualCash, 2)); ?></strong>
                                                        <br><small class="text-muted">Actual Cash Received</small>
                                                        
                                                            <small class="text-info">
                                                                Sale: <?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($saleAmount, 2)); ?>

                                                            </small>
                                                            <br><small class="text-warning">
                                                                <i class="fas fa-minus-circle"></i> Exchange: <?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($exchangeValue, 2)); ?>

                                                            </small>
                                                        
                                                            <br><small class="text-danger">Due: <?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($sale->due_amount, 2)); ?></small>
                                                            <br><small class="text-success">Profit: <?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($sale->profit, 2)); ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-secondary"><?php echo e(ucfirst($sale->payment_method)); ?></span>
                                                    </td>
                                                    <td>
                                                        <?php if($sale->payment_status == 'paid'): ?>
                                                            <span class="badge badge-success"><i class="fas fa-check"></i> Paid</span>
                                                        <?php elseif($sale->payment_status == 'unpaid'): ?>
                                                            <span class="badge badge-danger"><i class="fas fa-times"></i> Unpaid</span>
                                                        <?php elseif($sale->payment_status == 'partial'): ?>
                                                            <span class="badge badge-warning"><i class="fas fa-clock"></i> Partial</span>
                                                        <?php else: ?>
                                                            <span class="badge badge-secondary"><?php echo e(ucfirst($sale->payment_status)); ?></span>
                                                        <?php 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>
                                                            
                                                            <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                                <!-- Direct Sale Actions -->
                                                                <a href="<?php echo e(route('sales.table.invoice.public', $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>
                                                            <?php else: ?>
                                                                <!-- Regular Sale Actions -->
                                                                <a href="<?php echo e(route('sales.table.invoice.public', $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>
                                                                
                                                                <?php if($sale->payment_status != 'paid'): ?>
                                                                    <button class="btn btn-sm btn-success mark-paid" 
                                                                            data-sale-id="<?php echo e($sale->id); ?>" 
                                                                            data-toggle="tooltip" 
                                                                            title="Mark as Paid" 
                                                                            data-placement="top">
                                                                        <i class="fas fa-check-circle"></i>
                                                                    </button>
                                                                <?php endif; ?>
                                                            <?php 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> 
                                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                                            Direct Sale Actions
                                                                        <?php else: ?>
                                                                            Sale Actions
                                                                        <?php endif; ?>
                                                                    </h6>
                                                                    
                                                                    <button class="dropdown-item toggle-details" type="button">
                                                                        <i class="fas fa-info-circle text-info"></i> View Details
                                                                    </button>
                                                                    
                                                                    <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                                        <!-- Direct Sale Specific Actions -->
                                                                        <a class="dropdown-item" href="<?php echo e(route('sales.table.invoice.public', $sale->id)); ?>" target="_blank">
                                                                            <i class="fas fa-file-invoice text-primary"></i> Full Invoice
                                                                        </a>
                                                                    <?php else: ?>
                                                                        <!-- Regular Sale Specific Actions -->
                                                                        <button class="dropdown-item quick-invoice" data-sale-id="<?php echo e($sale->id); ?>" type="button">
                                                                            <i class="fas fa-receipt text-dark"></i> Quick Print
                                                                        </button>
                                                                        
                                                                        <a class="dropdown-item" href="<?php echo e(route('sales.table.invoice.public', $sale->id)); ?>" target="_blank">
                                                                            <i class="fas fa-file-invoice text-primary"></i> Full Invoice
                                                                        </a>
                                                                        
                                                                        <?php 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="<?php echo e(route('sales.edit', $sale->id)); ?>">
                                                                                <i class="fas fa-edit text-warning"></i> Edit Sale
                                                                            </a>
                                                                        <?php endif; ?>
                                                                    <?php endif; ?>
                                                                    
                                                                    <?php if($sale->customer): ?>
                                                                        <div class="dropdown-divider"></div>
                                                                        <a class="dropdown-item" href="<?php echo e(route('customers.show', $sale->customer->id)); ?>">
                                                                            <i class="fas fa-user text-info"></i> View Customer
                                                                        </a>
                                                                    <?php endif; ?>
                                                                    
                                                                    <div class="dropdown-divider"></div>
                                                                    <h6 class="dropdown-header text-danger"><i class="fas fa-exclamation-triangle"></i> Danger Zone</h6>
                                                                    <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                                        <button class="dropdown-item text-danger" onclick="confirmDirectSaleDelete('<?php echo e(str_replace('DS-', '', $sale->id)); ?>')" type="button">
                                                                            <i class="fas fa-trash"></i> Delete Direct Sale
                                                                        </button>
                                                                    <?php else: ?>
                                                                        <button class="dropdown-item text-danger" onclick="confirmDelete(<?php echo e($sale->id); ?>)" type="button">
                                                                            <i class="fas fa-trash"></i> Delete Sale
                                                                        </button>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Hidden forms for delete fallback -->
                                                        <?php if(isset($sale->type) && $sale->type == 'direct_sale'): ?>
                                                            <form id="delete-direct-form-<?php echo e(str_replace('DS-', '', $sale->id)); ?>" action="<?php echo e(route('direct-sales.destroy', str_replace('DS-', '', $sale->id))); ?>" method="POST" style="display: none;">
                                                                <?php echo csrf_field(); ?>
                                                                <?php echo method_field('DELETE'); ?>
                                                            </form>
                                                        <?php else: ?>
                                                            <form id="delete-form-<?php echo e($sale->id); ?>" action="<?php echo e(route('sales.destroy', $sale->id)); ?>" method="POST" style="display: none;">
                                                                <?php echo csrf_field(); ?>
                                                                <?php echo method_field('DELETE'); ?>
                                                            </form>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </tbody>
                                        <tfoot class="thead-light">
                                            <tr>
                                                <th colspan="6"><strong>Totals:</strong></th>
                                                <th><strong><?php echo e($all_settings->currency ?? 'BDT'); ?> <?php echo e(number_format($sales->sum('total_amount'), 2)); ?></strong></th>
                                                <th colspan="3"></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                            <!-- Pagination -->
                            <div class="card-footer clearfix">
                                <?php echo e($sales->links()); ?>

                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </section>

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

    <!-- Modern Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" role="dialog" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header bg-danger text-white">
            <h5 class="modal-title" id="deleteConfirmModalLabel">
              <i class="fas fa-exclamation-triangle"></i> Confirm Delete
            </h5>
            <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p class="font-weight-bold mb-2" id="deleteConfirmMessage">Are you sure you want to delete this sale?</p>
            <ul class="text-danger mb-0" id="deleteConfirmDetails">
              <li>This action cannot be undone.</li>
              <li>Sale record and all associated data will be permanently removed.</li>
            </ul>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-danger" id="deleteConfirmBtn"><i class="fas fa-trash"></i> Delete</button>
          </div>
        </div>
      </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('script'); ?>
<!-- Toastr JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<!-- Notification System -->
<script src="<?php echo e(asset('assets/js/notification-system.js')); ?>"></script>

<!-- Global Delete Functions - Available Immediately -->
<script>
    // Initialize notification system variable
    let notificationSystem;
    
    // GLOBAL DELETE FUNCTIONS - MUST BE AVAILABLE IMMEDIATELY FOR onclick HANDLERS
    
    // Regular sale delete confirmation
    window.confirmDelete = function(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.')) {
            window.performSaleDeletion(saleId);
        } else {
            console.log('User cancelled deletion');
        }
    };
    
    // Direct sale delete confirmation
    window.confirmDirectSaleDelete = function(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.')) {
            window.performDirectSaleDeletion(directSaleId);
        } else {
            console.log('User cancelled direct sale deletion');
        }
    };
    
    // Regular sale deletion logic
    window.performSaleDeletion = function(saleId) {
        console.log('Performing deletion for sale ID:', saleId);
        
        // Show loading state
        var deleteBtn = $('[onclick*="confirmDelete(' + saleId + ')"]');
        if (deleteBtn.length) {
            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');
        
        $.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) {
                    if (typeof notificationSystem !== 'undefined' && notificationSystem) {
                        notificationSystem.delete('Sale Deleted!', 'Sale record has been permanently removed');
                    } else {
                        toastr.success('Sale deleted successfully', 'Success');
                    }
                    
                    // Remove the deleted row from DataTable
                    if (typeof $.fn.DataTable !== 'undefined' && $('#salesTable').length) {
                        var table = $('#salesTable').DataTable();
                        var row = deleteBtn.closest('tr');
                        table.row(row).remove().draw(false);
                    } else {
                        location.reload(); // Fallback: reload page
                    }
                } else {
                    toastr.error(response.message || 'Failed to delete sale', 'Error');
                    if (deleteBtn.length) {
                        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();
            }
        });
    };
    
    // Direct sale deletion logic
    window.performDirectSaleDeletion = function(directSaleId) {
        console.log('Performing direct sale deletion for ID:', directSaleId);
        
        // Show loading state
        var deleteBtn = $('[onclick*="confirmDirectSaleDelete(\'' + directSaleId + '\')"]');
        if (deleteBtn.length) {
            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');
        
        $.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) {
                    if (typeof notificationSystem !== 'undefined' && notificationSystem) {
                        notificationSystem.delete('Direct Sale Deleted!', 'Direct sale record has been permanently removed');
                    } else {
                        toastr.success('Direct sale deleted successfully', 'Success');
                    }
                    
                    // Remove the deleted row from DataTable
                    if (typeof $.fn.DataTable !== 'undefined' && $('#salesTable').length) {
                        var table = $('#salesTable').DataTable();
                        var row = deleteBtn.closest('tr');
                        table.row(row).remove().draw(false);
                    } else {
                        location.reload(); // Fallback: reload page
                    }
                } else {
                    toastr.error(response.message || 'Failed to delete direct sale', 'Error');
                    if (deleteBtn.length) {
                        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();
            }
        });
    };
    
    // Modern popup for delete confirmation
    let pendingDeleteType = null;
    let pendingDeleteId = null;

    // Override global delete functions to use modal
    window.confirmDelete = function(saleId) {
        pendingDeleteType = 'sale';
        pendingDeleteId = saleId;
        $('#deleteConfirmModalLabel').html('<i class="fas fa-exclamation-triangle"></i> Confirm Delete');
        $('#deleteConfirmMessage').text('Are you sure you want to delete this sale?');
        $('#deleteConfirmDetails').html('<li>This action cannot be undone.</li><li>Sale record and all associated data will be permanently removed.</li>');
        $('#deleteConfirmBtn').removeClass('btn-warning').addClass('btn-danger').html('<i class="fas fa-trash"></i> Delete');
        $('#deleteConfirmModal').modal('show');
    };

    window.confirmDirectSaleDelete = function(directSaleId) {
        pendingDeleteType = 'directSale';
        pendingDeleteId = directSaleId;
        $('#deleteConfirmModalLabel').html('<i class="fas fa-exclamation-triangle"></i> Confirm Direct Sale Delete');
        $('#deleteConfirmMessage').text('Are you sure you want to delete this direct sale?');
        $('#deleteConfirmDetails').html('<li>This action cannot be undone.</li><li>Direct sale record and all associated data will be permanently removed.</li>');
        $('#deleteConfirmBtn').removeClass('btn-danger').addClass('btn-warning').html('<i class="fas fa-trash"></i> Delete Direct Sale');
        $('#deleteConfirmModal').modal('show');
    };

    // Handle modal delete button
    $('#deleteConfirmBtn').off('click').on('click', function() {
        $('#deleteConfirmModal').modal('hide');
        if (pendingDeleteType === 'sale') {
            window.performSaleDeletion(pendingDeleteId);
        } else if (pendingDeleteType === 'directSale') {
            window.performDirectSaleDeletion(pendingDeleteId);
        }
        pendingDeleteType = null;
        pendingDeleteId = null;
    });
    
    // Initialize notification system when available
    $(document).ready(function() {
        try {
            notificationSystem = new NotificationSystem();
            console.log('✅ Notification system initialized');
        } catch(e) {
            console.log('⚠️  Notification system not available, using toastr fallback');
        }
        
        // Verify functions are available
        console.log('✅ Global delete functions available:', {
            confirmDelete: typeof window.confirmDelete,
            confirmDirectSaleDelete: typeof window.confirmDirectSaleDelete,
            performSaleDeletion: typeof window.performSaleDeletion,
            performDirectSaleDeletion: typeof window.performDirectSaleDeletion
        });
    });
</script>

<!-- DataTable and Page Functionality -->
<script>
    $(document).ready(function() {
            
        // 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 {
                        toastr.success('Sale deleted successfully', 'Success');
                    }
                    
                    // Remove the deleted row from DataTable
                    var table = $('#salesTable').DataTable();
                    var row = deleteBtn.closest('tr');
                    table.row(row).remove().draw(false); // false keeps current page
                } else {
                    if (typeof notificationSystem !== 'undefined') {
                        notificationSystem.showError(response.message || 'Failed to delete sale', 'Delete Failed');
                    } else {
                        toastr.error(response.message || 'Failed to delete sale', 'Error');
                    }
                    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();
            }
        });
    }
        
        // Use modern confirmation dialog if available, fallback to native confirm
        if (typeof notificationSystem !== 'undefined' && notificationSystem && notificationSystem.confirm) {
            notificationSystem.confirm({
                title: 'Delete Direct Sale?',
                message: 'This action cannot be undone and will remove:\n• Direct sale record\n• All associated data',
                type: 'danger',
                confirmText: 'Delete Direct Sale',
                cancelText: 'Cancel',
                onConfirm: () => {
                    performDirectSaleDeletion(directSaleId);
                },
                onCancel: () => {
                    console.log('User cancelled direct sale deletion');
                }
            });
        } else 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.')) {
            performDirectSaleDeletion(directSaleId);
        } else {
            console.log('User cancelled direct sale deletion');
        }
    }
    
    // Make it globally accessible
    window.confirmDirectSaleDelete = confirmDirectSaleDelete;

    // Extracted direct sale deletion logic
    function performDirectSaleDeletion(directSaleId) {
        console.log('Performing direct sale deletion for ID:', directSaleId);
        
        // Show loading state
        var deleteBtn = $('[onclick*="confirmDirectSaleDelete(\'' + directSaleId + '\')"]');
        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-direct-form-' + directSaleId).submit();
            return;
        }
        
        $.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 {
                        toastr.success('Direct sale deleted successfully', 'Success');
                    }
                    
                    // Remove the deleted row from DataTable
                    var table = $('#salesTable').DataTable();
                    var row = deleteBtn.closest('tr');
                    table.row(row).remove().draw(false); // false keeps current page
                } else {
                    if (typeof notificationSystem !== 'undefined') {
                        notificationSystem.showError(response.message || 'Failed to delete direct sale', 'Delete Failed');
                    } else {
                        toastr.error(response.message || 'Failed to delete direct sale', 'Error');
                    }
                    deleteBtn.html(originalText);
                    deleteBtn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Direct sale 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-direct-form-' + directSaleId).submit();
            }
        });
    }
    
    // Make all functions globally accessible immediately
    window.confirmDelete = confirmDelete;
    window.confirmDirectSaleDelete = confirmDirectSaleDelete;
    window.performSaleDeletion = performSaleDeletion;
    window.performDirectSaleDeletion = performDirectSaleDeletion;
    
    // Initialize notification system after functions are defined
    try {
        notificationSystem = new NotificationSystem();
        console.log('Notification system initialized:', notificationSystem);
    } catch(e) {
        console.log('Notification system not available, using fallback');
    }
    
    // Log that functions are available
    console.log('Global delete functions are now available:', {
        confirmDelete: typeof window.confirmDelete,
        confirmDirectSaleDelete: typeof window.confirmDirectSaleDelete,
        performSaleDeletion: typeof window.performSaleDeletion,
        performDirectSaleDeletion: typeof window.performDirectSaleDeletion
    });
</script>

<!-- DataTable and page functionality -->
<script>
        
    $(document).ready(function() {
            console.log('Initializing Sales History DataTable and Filters...');
            
            // Initialize DataTables with enhanced search and filter capabilities
            var table = $('#salesTable').DataTable({
                "paging": true,
                "lengthChange": true,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                "pageLength": 25,
                "order": [[1, "desc"]],
                "language": {
                    "search": "Quick Search:",
                    "lengthMenu": "Show _MENU_ entries per page",
                    "info": "Showing _START_ to _END_ of _TOTAL_ sales records",
                    "infoEmpty": "No sales records found",
                    "infoFiltered": "(filtered from _MAX_ total records)"
                },
                "columnDefs": [
                    {
                        "targets": [9], // Actions column
                        "orderable": false,
                        "searchable": false
                    }
                ],
                "drawCallback": function(settings) {
                    console.log('DataTable redrawn, rows visible:', settings.aiDisplay.length);
                    // Update summary cards whenever table is redrawn
                    setTimeout(updateSummaryCards, 50);
                },
                "initComplete": function(settings, json) {
                    console.log('DataTable initialized with', settings.aoData.length, 'total rows');
                }
            });
            
            // Make table variable globally accessible for debugging
            window.salesTable = table;
            
            // Enhanced filter functionality with proper date parsing
            function applyFilters() {
                var dateFilter = $('#dateFilter').val();
                var saleTypeFilter = $('#saleTypeFilter').val();
                var paymentStatusFilter = $('#paymentStatusFilter').val();
                var globalSearch = $('#globalSearch').val();
                
                console.log('Applying filters:', {dateFilter, saleTypeFilter, paymentStatusFilter, globalSearch});
                
                // Clear existing custom search functions
                $.fn.dataTable.ext.search = [];
                
                // Apply global search to DataTable
                if (globalSearch) {
                    table.search(globalSearch);
                } else {
                    table.search('');
                }
                
                // Date filter logic with proper HTML parsing
                if (dateFilter && dateFilter !== 'all') {
                    var today = new Date();
                    today.setHours(0, 0, 0, 0); // Start of today
                    
                    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
                        if (settings.nTable.id !== 'salesTable') return true;
                        
                        var dateColumn = data[1]; // Date column
                        if (!dateColumn) return false;
                        
                        // Extract date from HTML content - look for date patterns
                        var dateMatch = dateColumn.match(/(\d{2}\s\w{3}\s\d{4})/);
                        if (!dateMatch) {
                            // Try alternative date formats
                            dateMatch = dateColumn.match(/(\d{4}-\d{2}-\d{2})/);
                            if (!dateMatch) {
                                // Try to extract any date-like pattern
                                var tempDiv = $('<div>').html(dateColumn);
                                var textContent = tempDiv.text().trim();
                                dateMatch = textContent.match(/(\d{2}\s\w{3}\s\d{4})/);
                            }
                        }
                        
                        if (!dateMatch) {
                            console.log('No date found in:', dateColumn);
                            return false;
                        }
                        
                        var rowDate = new Date(dateMatch[1]);
                        if (isNaN(rowDate.getTime())) {
                            console.log('Invalid date parsed:', dateMatch[1]);
                            return false;
                        }
                        rowDate.setHours(0, 0, 0, 0);
                        
                        switch(dateFilter) {
                            case 'today':
                                return rowDate.getTime() === today.getTime();
                            case 'yesterday':
                                var yesterday = new Date(today);
                                yesterday.setDate(yesterday.getDate() - 1);
                                return rowDate.getTime() === yesterday.getTime();
                            case 'last7':
                                var last7Days = new Date(today);
                                last7Days.setDate(last7Days.getDate() - 7);
                                return rowDate >= last7Days && rowDate <= today;
                            case 'last30':
                                var last30Days = new Date(today);
                                last30Days.setDate(last30Days.getDate() - 30);
                                return rowDate >= last30Days && rowDate <= today;
                            case 'last90':
                                var last90Days = new Date(today);
                                last90Days.setDate(last90Days.getDate() - 90);
                                return rowDate >= last90Days && rowDate <= today;
                            case 'last365':
                                var last365Days = new Date(today);
                                last365Days.setDate(last365Days.getDate() - 365);
                                return rowDate >= last365Days && rowDate <= today;
                            case 'this_month':
                                var thisMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                                return rowDate >= thisMonth && rowDate <= today;
                            case 'last_month':
                                var lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                                var lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
                                return rowDate >= lastMonth && rowDate <= lastMonthEnd;
                            case 'custom':
                                var startDate = $('#startDate').val();
                                var endDate = $('#endDate').val();
                                if (startDate && endDate) {
                                    var start = new Date(startDate);
                                    var end = new Date(endDate);
                                    start.setHours(0, 0, 0, 0);
                                    end.setHours(23, 59, 59, 999);
                                    return rowDate >= start && rowDate <= end;
                                }
                                return true;
                            default:
                                return true;
                        }
                    });
                }
                
                // Sale type filter with improved matching
                if (saleTypeFilter && saleTypeFilter !== 'all') {
                    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
                        if (settings.nTable.id !== 'salesTable') return true;
                        
                        var saleTypeColumn = data[0]; // ID column contains sale type badges
                        if (!saleTypeColumn) return false;
                        
                        switch(saleTypeFilter) {
                            case 'regular_sale':
                                return saleTypeColumn.includes('Regular Sale') || saleTypeColumn.includes('badge-primary');
                            case 'direct_sale':
                                return saleTypeColumn.includes('Direct Sale') || saleTypeColumn.includes('badge-warning');
                            case 'with_exchange':
                                return saleTypeColumn.includes('With Exchange') || saleTypeColumn.includes('exchange-alt');
                            default:
                                return true;
                        }
                    });
                }
                
                // Payment status filter with improved matching
                if (paymentStatusFilter && paymentStatusFilter !== 'all') {
                    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
                        if (settings.nTable.id !== 'salesTable') return true;
                        
                        var statusColumn = data[8]; // Status column
                        if (!statusColumn) return false;
                        
                        var statusText = statusColumn.toLowerCase();
                        return statusText.includes(paymentStatusFilter.toLowerCase());
                    });
                }
                
                // Apply filters and update summaries
                table.draw();
                
                // Update both filter summary and summary cards
                setTimeout(function() {
                    updateFilterSummary();
                    updateSummaryCards();
                }, 100); // Small delay to ensure table is redrawn
                
                console.log('Filters applied successfully');
            }
            
            // Update summary cards with filtered data
            function updateSummaryCards() {
                console.log('Updating summary cards with filtered data...');
                
                // Add loading animation to cards
                $('.small-box h3').addClass('text-muted');
                
                // Get filtered row data
                var filteredRows = table.rows({filter: 'applied'}).data();
                var totalRows = filteredRows.length;
                
                // Initialize counters
                var totalRevenue = 0;
                var partialPayments = 0;
                var unpaidSales = 0;
                var salesWithExchanges = 0;
                var totalExchangeValue = 0;
                var totalExchangeItems = 0;
                
                // Get currency symbol
                var currency = '<?php echo e($all_settings->currency ?? "BDT"); ?>';
                
                // Parse each filtered row
                for (var i = 0; i < filteredRows.length; i++) {
                    var rowData = filteredRows[i];
                    
                    // Extract actual cash amount from column 6 (Actual Cash)
                    var actualCashColumn = rowData[6];
                    var actualCashMatch = actualCashColumn.match(/[\d,]+\.?\d*/);
                    if (actualCashMatch) {
                        var amount = parseFloat(actualCashMatch[0].replace(/,/g, ''));
                        if (!isNaN(amount)) {
                            totalRevenue += amount;
                        }
                    }
                    
                    // Check payment status from column 8
                    var statusColumn = rowData[8].toLowerCase();
                    if (statusColumn.includes('partial')) {
                        partialPayments++;
                    } else if (statusColumn.includes('unpaid')) {
                        unpaidSales++;
                    }
                    
                    // Check for exchanges from column 0 (ID column contains badges)
                    var idColumn = rowData[0];
                    if (idColumn.includes('With Exchange') || idColumn.includes('exchange-alt')) {
                        salesWithExchanges++;
                    }
                    
                    // Extract exchange values if present
                    var exchangeMatch = actualCashColumn.match(/Exchange[^>]*>[\s\S]*?([\d,]+\.?\d*)/);
                    if (exchangeMatch) {
                        var exchangeAmount = parseFloat(exchangeMatch[1].replace(/,/g, ''));
                        if (!isNaN(exchangeAmount)) {
                            totalExchangeValue += exchangeAmount;
                            totalExchangeItems++;
                        }
                    }
                }
                
                // Calculate actual cash (total revenue is already actual cash from our extraction)
                var actualCash = totalRevenue;
                var saleAmount = totalRevenue + totalExchangeValue;
                var exchangePercentage = saleAmount > 0 ? ((totalExchangeValue / saleAmount) * 100) : 0;
                
                // Update main summary cards
                $('#filteredTotalSales').text(totalRows);
                $('#filteredTotalRevenue').text(currency + ' ' + numberFormat(totalRevenue));
                $('#filteredPartialPayments').text(partialPayments);
                $('#filteredUnpaidSales').text(unpaidSales);
                
                // Update exchange summary cards
                $('#filteredActualCash').text(currency + ' ' + numberFormat(actualCash));
                $('#filteredSalesWithExchanges').text(salesWithExchanges);
                $('#filteredTotalExchangeItems').text(totalExchangeItems);
                $('#filteredTotalExchangeDiscount').text(currency + ' ' + numberFormat(totalExchangeValue));
                
                // Update status texts
                var filterStatus = getFilterStatusText();
                $('#filteredSalesStatus').text(filterStatus);
                $('#filteredRevenueStatus').text(filterStatus);
                $('#filteredPartialStatus').text(filterStatus);
                $('#filteredUnpaidStatus').text(filterStatus);
                $('#filteredExchangesSubtext').text(filterStatus + ' with exchanges');
                $('#filteredExchangeItemsSubtext').text('Items from ' + filterStatus.toLowerCase());
                
                // Update calculation display
                $('#filteredActualCashCalc').html(
                    '<i class="fas fa-calculator"></i> Sales: ' + numberFormat(saleAmount) + 
                    ' - Exchanges: ' + numberFormat(totalExchangeValue)
                );
                
                // Update exchange percentage
                $('#filteredExchangePercentage').text(exchangePercentage.toFixed(1) + '%');
                
                // Remove loading animation
                $('.small-box h3').removeClass('text-muted');
                
                console.log('Summary updated:', {
                    totalRows: totalRows,
                    totalRevenue: totalRevenue,
                    partialPayments: partialPayments,
                    unpaidSales: unpaidSales,
                    salesWithExchanges: salesWithExchanges,
                    totalExchangeValue: totalExchangeValue
                });
            }
            
            // Get filter status text for display
            function getFilterStatusText() {
                var dateFilter = $('#dateFilter').val();
                var saleTypeFilter = $('#saleTypeFilter').val();
                var paymentStatusFilter = $('#paymentStatusFilter').val();
                var globalSearch = $('#globalSearch').val();
                
                if (dateFilter !== 'all') {
                    return $('#dateFilter option:selected').text();
                } else if (saleTypeFilter !== 'all') {
                    return $('#saleTypeFilter option:selected').text();
                } else if (paymentStatusFilter !== 'all') {
                    return $('#paymentStatusFilter option:selected').text();
                } else if (globalSearch) {
                    return 'Search Results';
                } else {
                    return 'All Records';
                }
            }
            
            // Number formatting helper
            function numberFormat(num) {
                return new Intl.NumberFormat('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }).format(num);
            }
            
            // Update filter summary
            function updateFilterSummary() {
                var activeFilters = [];
                var dateFilter = $('#dateFilter').val();
                var saleTypeFilter = $('#saleTypeFilter').val();
                var paymentStatusFilter = $('#paymentStatusFilter').val();
                var globalSearch = $('#globalSearch').val();
                
                if (dateFilter !== 'all') {
                    activeFilters.push('Date: ' + $('#dateFilter option:selected').text());
                }
                if (saleTypeFilter !== 'all') {
                    activeFilters.push('Type: ' + $('#saleTypeFilter option:selected').text());
                }
                if (paymentStatusFilter !== 'all') {
                    activeFilters.push('Status: ' + $('#paymentStatusFilter option:selected').text());
                }
                if (globalSearch) {
                    activeFilters.push('Search: "' + globalSearch + '"');
                }
                
                if (activeFilters.length > 0) {
                    $('#filterSummaryText').text(activeFilters.join(', '));
                    $('#filterSummary').show();
                } else {
                    $('#filterSummary').hide();
                }
            }
            
            // Enhanced clear filters function
            function clearFilters() {
                $('#dateFilter').val('all');
                $('#saleTypeFilter').val('all');
                $('#paymentStatusFilter').val('all');
                $('#globalSearch').val('');
                $('#startDate').val('');
                $('#endDate').val('');
                $('#customDateRange').slideUp();
                
                // Clear all custom search functions
                $.fn.dataTable.ext.search = [];
                
                // Clear table search and redraw
                table.search('').columns().search('').draw();
                
                // Hide filter summary
                $('#filterSummary').hide();
                
                // Update summary cards to show all data
                setTimeout(function() {
                    updateSummaryCards();
                }, 100);
                
                // Show success notification
                toastr.success('All filters have been cleared', 'Filters Cleared');
                console.log('All filters cleared');
            }
            
            // Enhanced event handlers with better feedback
            $('#dateFilter').on('change', function() {
                console.log('Date filter changed to:', $(this).val());
                if ($(this).val() === 'custom') {
                    $('#customDateRange').slideDown();
                } else {
                    $('#customDateRange').slideUp();
                    applyFilters(); // Auto-apply when not custom
                }
            });
            
            // Auto-apply when custom date range changes
            $('#startDate, #endDate').on('change', function() {
                console.log('Custom date range changed:', $('#startDate').val(), $('#endDate').val());
                if ($('#dateFilter').val() === 'custom' && $('#startDate').val() && $('#endDate').val()) {
                    applyFilters();
                }
            });
            
            // Auto-apply filters for other controls
            $('#saleTypeFilter, #paymentStatusFilter').on('change', function() {
                console.log('Filter changed:', $(this).attr('id'), $(this).val());
                applyFilters();
            });
            
            // Global search with debounce
            $('#globalSearch').on('input', debounce(function() {
                console.log('Global search:', $(this).val());
                applyFilters();
            }, 500));
            
            $('#clearFilters').on('click', clearFilters);
            
            // Debounce function for search input
            function debounce(func, wait) {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func.apply(this, args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            }
            
            // Export filtered data
            $('#exportFiltered').on('click', function() {
                var filteredData = table.rows({ filter: 'applied' }).data();
                console.log('Filtered data ready for export:', filteredData.length, 'rows');
                // You can add actual CSV/Excel export logic here
                alert('Export functionality ready! Found ' + filteredData.length + ' filtered rows.');
            });
            
            // Enhanced test filter function
            window.testDateFilter = function() {
                console.log('Testing date filter...');
                $('#dateFilter').val('yesterday').trigger('change');
                setTimeout(function() {
                    var filteredCount = table.rows({filter: 'applied'}).data().length;
                    console.log('Filtered results:', filteredCount);
                    toastr.info('Filter test completed. Found ' + filteredCount + ' matching records.', 'Filter Test');
                }, 100);
            };
            
            // Add filter debugging
            window.debugFilters = function() {
                console.log('=== FILTER DEBUG INFO ===');
                console.log('Date Filter:', $('#dateFilter').val());
                console.log('Sale Type Filter:', $('#saleTypeFilter').val());
                console.log('Payment Status Filter:', $('#paymentStatusFilter').val());
                console.log('Global Search:', $('#globalSearch').val());
                console.log('Total rows:', table.rows().data().length);
                console.log('Filtered rows:', table.rows({filter: 'applied'}).data().length);
                console.log('Custom search functions:', $.fn.dataTable.ext.search.length);
                
                // Show sample data from first row
                var firstRow = table.row(0).data();
                if (firstRow) {
                    console.log('Sample row data:');
                    firstRow.forEach(function(cell, index) {
                        console.log('Column ' + index + ':', cell);
                    });
                }
            };
            
            // Keyboard shortcuts
            $(document).on('keydown', function(e) {
                if (e.key === 'f' || e.key === 'F') {
                    e.preventDefault();
                    $('.dataTables_filter input').focus();
                } else if (e.ctrlKey && e.key === 'c') {
                    e.preventDefault();
                    clearFilters();
                } else if (e.ctrlKey && e.key === 'e') {
                    e.preventDefault();
                    $('#exportFiltered').click();
                } else if (e.ctrlKey && e.key === '1') {
                    e.preventDefault();
                    $('#dateFilter').val('today').trigger('change');
                } else if (e.ctrlKey && e.key === '7') {
                    e.preventDefault();
                    $('#dateFilter').val('last_7_days').trigger('change');
                }
            });
            
            // Debug: Make sure functions are available globally
            console.log('Delete functions loaded:', {
                confirmDelete: typeof window.confirmDelete,
                confirmDirectSaleDelete: typeof window.confirmDirectSaleDelete,
                performSaleDeletion: typeof window.performSaleDeletion,
                performDirectSaleDeletion: typeof window.performDirectSaleDeletion
            });
            
            // Verify functions are accessible globally
            if (typeof window.confirmDelete === 'function') {
                console.log('✅ confirmDelete is available globally');
            } else {
                console.error('❌ confirmDelete is NOT available globally');
            }
            
            if (typeof window.confirmDirectSaleDelete === 'function') {
                console.log('✅ confirmDirectSaleDelete is available globally');
            } else {
                console.error('❌ confirmDirectSaleDelete is NOT available globally');
            }
            
            // Initialize Toastr settings
            toastr.options = {
                "closeButton": true,
                "debug": false,
                "newestOnTop": true,
                "progressBar": true,
                "positionClass": "toast-top-right",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };
            
            // Initialize filter summary and summary cards on load
            updateFilterSummary();
            setTimeout(function() {
                updateSummaryCards();
            }, 200);
            
            // Add success message
            console.log('✅ Sales History filter system initialized successfully!');
            console.log('📊 Total sales loaded:', table.rows().data().length);
            
            // Show initialization complete message
            setTimeout(function() {
                toastr.success('Sales History loaded with dynamic summary cards!', 'System Ready');
            }, 500);
        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\pos v24.4\resources\views/sales/history.blade.php ENDPATH**/ ?>