<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    
    <title>POS Reports - Mariyappa Nadar Ricemill</title>
    
    <!-- Custom fonts for this template-->
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
    
    <!-- Custom styles for this template-->
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    
    <!-- DataTables CSS -->
    <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
    
    <style>
        .report-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            transition: all 0.3s;
        }
        
        .report-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 2rem 0 rgba(58, 59, 69, 0.2);
        }
        
        .report-header {
            background: linear-gradient(45deg, #4e73df, #224abe);
            color: white;
            border-radius: 10px 10px 0 0;
            padding: 1rem;
        }
        
        .stats-card {
            background: linear-gradient(45deg, #1cc88a, #13855c);
            border-radius: 10px;
            color: white;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .btn-edit {
            background: #f6c23e;
            border-color: #f6c23e;
            color: #3a3b45;
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
        
        .btn-edit:hover {
            background: #dda20a;
            border-color: #d39e00;
            color: #3a3b45;
        }
        
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
        }
        
        .edit-form {
            background: #f8f9fc;
            border-radius: 10px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .modal-header {
            background: linear-gradient(45deg, #4e73df, #224abe);
            color: white;
            border-radius: 10px 10px 0 0;
        }
        
        /* Mobile Responsive Styles */
        @media (max-width: 768px) {
            .stats-card {
                margin-bottom: 0.5rem;
                padding: 1rem;
            }
            
            .stats-number {
                font-size: 1.5rem;
            }
            
            .btn-group {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .btn-group .btn {
                width: 100%;
            }
            
            .table-responsive {
                font-size: 0.85rem;
            }
            
            .btn-sm {
                padding: 0.2rem 0.4rem;
                font-size: 0.7rem;
            }
            
            .modal-dialog {
                margin: 0.5rem;
            }
            
            /* Hide table on mobile and show cards instead */
            #salesTable_wrapper {
                display: none !important;
            }
            
            #mobileCardsContainer {
                display: block !important;
            }
            
            /* Hide edit/delete buttons in mobile view */
            .mobile-hide-actions .btn-edit,
            .mobile-hide-actions .btn-danger {
                display: none !important;
            }
        }
        
        @media (max-width: 480px) {
            .container-fluid {
                padding: 0.5rem;
            }
            
            .h3 {
                font-size: 1.2rem;
            }
            
            .report-card {
                margin-bottom: 0.5rem;
            }
            
            .stats-number {
                font-size: 1.2rem;
            }
            
            .btn-edit, .btn-info {
                padding: 0.15rem 0.3rem;
                font-size: 0.65rem;
            }
        }
        
        /* Mobile Cards Styles */
        .mobile-transaction-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
            overflow: hidden;
            border: 1px solid #e0e0e0;
            transition: all 0.3s ease;
        }
        
        .mobile-transaction-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        }
        
        .mobile-card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            position: relative;
        }
        
        .mobile-card-header .date-badge {
            background: rgba(255,255,255,0.2);
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            float: right;
            margin-top: -0.25rem;
        }
        
        .mobile-card-body {
            padding: 1rem;
        }
        
        .customer-info {
            margin-bottom: 0.75rem;
        }
        
        .customer-name {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 0.25rem;
        }
        
        .transaction-details {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
            padding: 0.75rem;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .amount-section {
            text-align: right;
        }
        
        .amount-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: #28a745;
            margin-bottom: 0.25rem;
        }
        
        .payment-method {
            font-size: 0.85rem;
            color: #6c757d;
        }
        
        .items-info {
            font-size: 0.9rem;
            color: #666;
        }
        
        .status-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 0.75rem;
            padding-top: 0.75rem;
            border-top: 1px solid #e9ecef;
        }
        
        .mobile-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .mobile-actions .btn {
            padding: 0.5rem;
            border-radius: 8px;
        }
        
        #mobileCardsContainer {
            display: none; /* Hidden by default, shown on mobile */
        }
        
        .mobile-search-box {
            margin-bottom: 1rem;
            padding: 0.75rem;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .mobile-search-input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 2rem;
            color: #666;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #ddd;
        }
    </style>
</head>

<body id="page-top">
    <!-- Page Wrapper -->
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include_once('includes/sidebar.php'); ?>
        
        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <!-- Main Content -->
            <div id="content">
                <!-- Topbar -->
                <?php include_once('includes/topbar.php'); ?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="fas fa-chart-line mr-2"></i>POS Reports & Analytics
                        </h1>
                        <div class="btn-group">
                            <a href="pos.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-cash-register mr-1"></i>Back to POS
                            </a>
                            <button class="btn btn-success btn-sm" onclick="exportData()">
                                <i class="fas fa-download mr-1"></i>Export
                            </button>
                        </div>
                    </div>

                    <!-- Date Filter Row -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card report-card">
                                <div class="card-body">
                                    <form id="dateFilterForm" class="row align-items-end">
                                        <div class="col-md-3">
                                            <label class="form-label">From Date</label>
                                            <input type="date" class="form-control" id="fromDate" value="<?php echo date('Y-m-01'); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">To Date</label>
                                            <input type="date" class="form-control" id="toDate" value="<?php echo date('Y-m-d'); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Customer</label>
                                            <select class="form-control" id="customerFilter">
                                                <option value="">All Customers</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-search mr-1"></i>Filter
                                            </button>
                                            <button type="button" class="btn btn-secondary ml-2" onclick="resetFilters()">
                                                <i class="fas fa-refresh mr-1"></i>Reset
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="stats-number" id="totalSales">₹0</div>
                                <div>Total Sales</div>
                                <small id="salesPeriod">This Month</small>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="stats-number" id="totalOrders">0</div>
                                <div>Total Orders</div>
                                <small id="ordersPeriod">This Month</small>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="stats-number" id="totalCustomers">0</div>
                                <div>Active Customers</div>
                                <small>This Period</small>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="stats-number" id="avgOrderValue">₹0</div>
                                <div>Avg Order Value</div>
                                <small>This Period</small>
                            </div>
                        </div>
                    </div>

                    <!-- Sales Report Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card report-card">
                                <div class="report-header">
                                    <h6 class="m-0 font-weight-bold">
                                        <i class="fas fa-receipt mr-2"></i>Sales Transactions
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <!-- Desktop Table View -->
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="salesTable" width="100%" cellspacing="0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Customer</th>
                                                    <th>Items</th>
                                                    <th>Payment Method</th>
                                                    <th>Amount</th>
                                                    <th>Paid</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody id="salesTableBody">
                                                <!-- Data will be loaded here -->
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Mobile Cards View -->
                                    <div id="mobileCardsContainer">
                                        <div class="mobile-search-box">
                                            <input type="text" id="mobileSearchInput" class="mobile-search-input" placeholder="🔍 Search transactions..." onkeyup="filterMobileCards()">
                                        </div>
                                        <div id="mobileCardsGrid">
                                            <!-- Mobile cards will be generated here -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include_once('includes/footer.php'); ?>
        </div>
        <!-- End of Content Wrapper -->
    </div>
    <!-- End of Page Wrapper -->

    <!-- Edit Bill Modal -->
    <div class="modal fade" id="editBillModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-edit mr-2"></i>Edit Bill
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editBillForm">
                        <input type="hidden" id="editPaymentId" name="payment_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Customer</label>
                                    <input type="text" class="form-control" id="editCustomerName" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Transaction Date</label>
                                    <input type="date" class="form-control" id="editTransactionDate" name="transaction_date">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Payment Method</label>
                                    <select class="form-control" id="editPaymentMethod" name="payment_method">
                                        <option value="Cash">Cash</option>
                                        <option value="UPI">UPI</option>
                                        <option value="Card">Card</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Cheque">Cheque</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Amount</label>
                                    <input type="number" class="form-control" id="editAmount" name="amount" step="0.01">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Reference Number</label>
                            <input type="text" class="form-control" id="editReferenceNumber" name="reference_number">
                        </div>
                        
                        <div class="form-group">
                            <label>Description</label>
                            <textarea class="form-control" id="editDescription" name="description" rows="3"></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label>Status</label>
                            <select class="form-control" id="editStatus" name="status">
                                <option value="Completed">Completed</option>
                                <option value="Pending">Pending</option>
                                <option value="Cancelled">Cancelled</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="updateBill()">
                        <i class="fas fa-save mr-1"></i>Save Changes
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- View Details Modal -->
    <div class="modal fade" id="viewDetailsModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-eye mr-2"></i>Transaction Details
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="transactionDetails">
                    <!-- Details will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="printBill()">
                        <i class="fas fa-print mr-1"></i>Print
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="js/sb-admin-2.min.js"></script>

    <!-- Page level plugins -->
    <script src="vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>

    <script>
        let salesTable;

        $(document).ready(function() {
            initializeDataTable();
            loadCustomers();
            loadSalesData();
            
            $('#dateFilterForm').on('submit', function(e) {
                e.preventDefault();
                loadSalesData();
            });
        });

        function initializeDataTable() {
            salesTable = $('#salesTable').DataTable({
                "responsive": true,
                "lengthChange": true,
                "autoWidth": false,
                "ordering": true,
                "info": true,
                "paging": true,
                "pageLength": 25,
                "order": [[0, "desc"]],
                "columnDefs": [
                    { "orderable": false, "targets": 7 } // Actions column
                ]
            });
        }

        function loadCustomers() {
            $.ajax({
                url: 'api/get-customers-search.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const select = $('#customerFilter');
                        select.html('<option value="">All Customers</option>');
                        response.data.forEach(customer => {
                            select.append(`<option value="${customer.ID}">${customer.CustomerName}</option>`);
                        });
                    }
                }
            });
        }

        function loadSalesData() {
            const fromDate = $('#fromDate').val();
            const toDate = $('#toDate').val();
            const customerId = $('#customerFilter').val();

            $.ajax({
                url: 'api/get-pos-reports.php',
                method: 'GET',
                data: {
                    from_date: fromDate,
                    to_date: toDate,
                    customer_id: customerId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        updateStatistics(response.statistics);
                        updateSalesTable(response.transactions);
                    } else {
                        console.error('Failed to load sales data:', response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sales data:', error);
                }
            });
        }

        function updateStatistics(stats) {
            $('#totalSales').text('₹' + parseFloat(stats.total_sales || 0).toLocaleString());
            $('#totalOrders').text(stats.total_orders || 0);
            $('#totalCustomers').text(stats.unique_customers || 0);
            $('#avgOrderValue').text('₹' + parseFloat(stats.avg_order_value || 0).toLocaleString());
        }

        function updateSalesTable(transactions) {
            salesTable.clear();

            transactions.forEach(transaction => {
                const row = [
                    new Date(transaction.TransactionDate).toLocaleDateString(),
                    transaction.CustomerName,
                    transaction.ItemCount + ' items',
                    transaction.PaymentMethod,
                    '₹' + parseFloat(transaction.Amount).toLocaleString(),
                    '₹' + parseFloat(transaction.PaidAmount || 0).toLocaleString(),
                    `<span class="badge badge-${getStatusColor(transaction.Status)}">${transaction.Status}</span>`,
                    `
                        <div class="btn-group">
                            <button class="btn btn-info btn-sm" onclick="viewDetails(${transaction.ID})" title="View Details">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-success btn-sm" onclick="printReceipt(${transaction.ID})" title="Print Receipt">
                                <i class="fas fa-print"></i>
                            </button>
                            <button class="btn btn-edit btn-sm" onclick="editBill(${transaction.ID})" title="Edit Bill">
                                <i class="fas fa-edit"></i>
                            </button>
                            ${transaction.Status !== 'Cancelled' ? `
                            <button class="btn btn-danger btn-sm" onclick="deleteBill(${transaction.ID}, '${transaction.CustomerName}', '${parseFloat(transaction.Amount).toLocaleString()}')" title="Delete Bill">
                                <i class="fas fa-trash"></i>
                            </button>
                            ` : ''}
                        </div>
                    `
                ];
                salesTable.row.add(row);
            });

            salesTable.draw();
            
            // Generate mobile cards
            generateMobileCards(transactions);
        }
        
        function generateMobileCards(transactions) {
            const mobileCardsGrid = document.getElementById('mobileCardsGrid');
            
            if (!transactions || transactions.length === 0) {
                mobileCardsGrid.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-receipt"></i>
                        <h5>No Transactions Found</h5>
                        <p>No sales data available for the selected period.</p>
                    </div>
                `;
                return;
            }
            
            let cardsHTML = '';
            
            transactions.forEach(transaction => {
                const transactionDate = new Date(transaction.TransactionDate);
                const formattedDate = transactionDate.toLocaleDateString('en-IN', {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                });
                const formattedTime = transactionDate.toLocaleTimeString('en-IN', {
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                const amount = parseFloat(transaction.Amount);
                const paidAmount = parseFloat(transaction.PaidAmount || 0);
                const balance = amount - paidAmount;
                
                cardsHTML += `
                    <div class="mobile-transaction-card" data-transaction-id="${transaction.ID}" data-customer="${transaction.CustomerName.toLowerCase()}" data-amount="${amount}">
                        <div class="mobile-card-header">
                            <div class="customer-name">${transaction.CustomerName}</div>
                            <div class="date-badge">${formattedDate}</div>
                        </div>
                        <div class="mobile-card-body">
                            <div class="transaction-details">
                                <div class="items-info">
                                    <i class="fas fa-shopping-bag mr-1"></i>
                                    ${transaction.ItemCount} item${transaction.ItemCount > 1 ? 's' : ''}
                                    <br>
                                    <small class="text-muted">${formattedTime}</small>
                                </div>
                                <div class="amount-section">
                                    <div class="amount-value">₹${amount.toLocaleString()}</div>
                                    <div class="payment-method">
                                        <i class="fas fa-${getPaymentIcon(transaction.PaymentMethod)} mr-1"></i>
                                        ${transaction.PaymentMethod}
                                    </div>
                                </div>
                            </div>
                            
                            ${balance > 0 ? `
                            <div class="alert alert-warning alert-sm mb-2">
                                <small><i class="fas fa-exclamation-triangle mr-1"></i>
                                Pending: ₹${balance.toLocaleString()}</small>
                            </div>
                            ` : ''}
                            
                            <div class="status-section">
                                <span class="badge badge-${getStatusColor(transaction.Status)}">${transaction.Status}</span>
                                <div class="mobile-actions mobile-hide-actions">
                                    <button class="btn btn-info btn-sm" onclick="viewDetails(${transaction.ID})" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn btn-success btn-sm" onclick="printReceipt(${transaction.ID})" title="Print">
                                        <i class="fas fa-print"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            mobileCardsGrid.innerHTML = cardsHTML;
        }
        
        function getPaymentIcon(paymentMethod) {
            const icons = {
                'Cash': 'money-bill-wave',
                'UPI': 'mobile-alt',
                'Card': 'credit-card',
                'Bank Transfer': 'university',
                'Cheque': 'money-check'
            };
            return icons[paymentMethod] || 'money-bill';
        }
        
        function filterMobileCards() {
            const searchTerm = document.getElementById('mobileSearchInput').value.toLowerCase();
            const cards = document.querySelectorAll('.mobile-transaction-card');
            
            cards.forEach(card => {
                const customerName = card.getAttribute('data-customer');
                const transactionId = card.getAttribute('data-transaction-id');
                const amount = card.getAttribute('data-amount');
                
                const isVisible = customerName.includes(searchTerm) || 
                                transactionId.includes(searchTerm) || 
                                amount.includes(searchTerm);
                
                card.style.display = isVisible ? 'block' : 'none';
            });
        }

        function getStatusColor(status) {
            switch(status) {
                case 'Completed': return 'success';
                case 'Pending': return 'warning';
                case 'Cancelled': return 'danger';
                default: return 'secondary';
            }
        }

        function editBill(paymentId) {
            // Redirect to POS page with edit mode and sale ID
            window.location.href = `pos.php?edit=${paymentId}`;
        }

        function deleteBill(saleId, customerName, amount) {
            const reason = prompt(`Are you sure you want to delete this bill?\n\nCustomer: ${customerName}\nAmount: ₹${amount}\n\nThis will:\n- Cancel the sale\n- Restore stock quantities\n- Reverse payment records\n\nPlease enter reason for deletion (optional):`);
            
            if (reason === null) {
                return; // User cancelled
            }
            
            // Confirm deletion
            if (!confirm(`This action cannot be undone. Are you absolutely sure you want to delete this bill?\n\nCustomer: ${customerName}\nAmount: ₹${amount}`)) {
                return;
            }
            
            $.ajax({
                url: 'api/delete-sale.php',
                method: 'POST',
                data: JSON.stringify({
                    sale_id: saleId,
                    reason: reason || 'Manual deletion from reports'
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert(`Bill deleted successfully!\n\nSale Number: ${response.data.sale_number}\nStock restored for ${response.data.items_restored} items\nDeletion Time: ${response.data.deletion_time}`);
                        loadSalesData(); // Reload the table
                    } else {
                        alert('Error deleting bill: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Delete error:', status, error, xhr.responseText);
                    alert('Error deleting bill. Please check console for details.');
                }
            });
        }

        function updateBill() {
            const formData = {
                payment_id: $('#editPaymentId').val(),
                transaction_date: $('#editTransactionDate').val(),
                payment_method: $('#editPaymentMethod').val(),
                amount: $('#editAmount').val(),
                reference_number: $('#editReferenceNumber').val(),
                description: $('#editDescription').val(),
                status: $('#editStatus').val()
            };

            $.ajax({
                url: 'api/update-payment.php',
                method: 'POST',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#editBillModal').modal('hide');
                        loadSalesData();
                        alert('Bill updated successfully!');
                    } else {
                        alert('Error updating bill: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('Error updating bill');
                }
            });
        }

        function viewDetails(paymentId) {
            $.ajax({
                url: 'api/get-payment-details.php',
                method: 'GET',
                data: { id: paymentId, include_items: true },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const payment = response.data;
                        let html = `
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>Transaction Information</h6>
                                    <table class="table table-sm">
                                        <tr><td><strong>Date:</strong></td><td>${new Date(payment.TransactionDate).toLocaleDateString()}</td></tr>
                                        <tr><td><strong>Customer:</strong></td><td>${payment.CustomerName}</td></tr>
                                        <tr><td><strong>Payment Method:</strong></td><td>${payment.PaymentMethod}</td></tr>
                                        <tr><td><strong>Reference:</strong></td><td>${payment.ReferenceNumber || 'N/A'}</td></tr>
                                        <tr><td><strong>Status:</strong></td><td><span class="badge badge-${getStatusColor(payment.Status)}">${payment.Status}</span></td></tr>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <h6>Amount Details</h6>
                                    <table class="table table-sm">
                                        <tr><td><strong>Amount:</strong></td><td>₹${parseFloat(payment.Amount).toLocaleString()}</td></tr>
                                        <tr><td><strong>Paid:</strong></td><td>₹${parseFloat(payment.PaidAmount || 0).toLocaleString()}</td></tr>
                                        <tr><td><strong>Balance:</strong></td><td>₹${(parseFloat(payment.Amount) - parseFloat(payment.PaidAmount || 0)).toLocaleString()}</td></tr>
                                    </table>
                                </div>
                            </div>
                        `;

                        if (payment.items && payment.items.length > 0) {
                            html += `
                                <h6>Items Purchased</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm table-striped">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th>Quantity</th>
                                                <th>Rate</th>
                                                <th>Total</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                            `;
                            
                            payment.items.forEach(item => {
                                html += `
                                    <tr>
                                        <td>${item.ProductName}</td>
                                        <td>${item.Quantity}</td>
                                        <td>₹${parseFloat(item.Rate).toLocaleString()}</td>
                                        <td>₹${(parseFloat(item.Rate) * parseFloat(item.Quantity)).toLocaleString()}</td>
                                    </tr>
                                `;
                            });
                            
                            html += '</tbody></table></div>';
                        }

                        if (payment.Description) {
                            html += `<h6>Notes</h6><p>${payment.Description}</p>`;
                        }

                        $('#transactionDetails').html(html);
                        $('#viewDetailsModal').modal('show');
                    }
                }
            });
        }

        function resetFilters() {
            $('#fromDate').val('<?php echo date('Y-m-01'); ?>');
            $('#toDate').val('<?php echo date('Y-m-d'); ?>');
            $('#customerFilter').val('');
            loadSalesData();
        }

        function exportData() {
            const fromDate = $('#fromDate').val();
            const toDate = $('#toDate').val();
            const customerId = $('#customerFilter').val();
            
            window.open(`api/export-pos-reports.php?from_date=${fromDate}&to_date=${toDate}&customer_id=${customerId}`, '_blank');
        }

        function printBill() {
            window.print();
        }

        // Print receipt function for 2-inch thermal printer
        function printReceipt(saleId) {
            const receiptUrl = `api/print-receipt.php?sale_id=${saleId}`;
            
            // Open receipt in new window for printing
            const receiptWindow = window.open('', '_blank', 'width=400,height=600,scrollbars=yes,resizable=yes');
            
            // Show loading message
            receiptWindow.document.write(`
                <html>
                    <head><title>Loading Receipt...</title></head>
                    <body style="font-family: Arial; text-align: center; padding: 50px;">
                        <h3>🧾 Generating Thermal Receipt...</h3>
                        <p>Please wait while we prepare your 2-inch thermal receipt.</p>
                        <div style="margin-top: 20px;">
                            <div style="display: inline-block; width: 30px; height: 30px; border: 3px solid #f3f3f3; border-top: 3px solid #007185; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                        </div>
                        <style>
                            @keyframes spin {
                                0% { transform: rotate(0deg); }
                                100% { transform: rotate(360deg); }
                            }
                        </style>
                    </body>
                </html>
            `);
            
            // Fetch receipt HTML
            $.ajax({
                url: receiptUrl,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Write receipt HTML to new window
                        receiptWindow.document.open();
                        receiptWindow.document.write(response.data.html);
                        receiptWindow.document.close();
                        
                        // Focus the window for printing
                        receiptWindow.focus();
                    } else {
                        receiptWindow.document.body.innerHTML = `
                            <div style="font-family: Arial; text-align: center; padding: 50px; color: red;">
                                <h3>❌ Receipt Error</h3>
                                <p>${response.message}</p>
                                <button onclick="window.close()" style="padding: 10px 20px; margin-top: 20px; background: #007185; color: white; border: none; border-radius: 4px; cursor: pointer;">Close Window</button>
                            </div>
                        `;
                    }
                },
                error: function(xhr, status, error) {
                    receiptWindow.document.body.innerHTML = `
                        <div style="font-family: Arial; text-align: center; padding: 50px; color: red;">
                            <h3>🔌 Connection Error</h3>
                            <p>Unable to generate receipt. Please try again.</p>
                            <p style="font-size: 12px; color: #666;">Error: ${error}</p>
                            <button onclick="window.close()" style="padding: 10px 20px; margin-top: 20px; background: #007185; color: white; border: none; border-radius: 4px; cursor: pointer;">Close Window</button>
                        </div>
                    `;
                }
            });
        }
    </script>
</body>
</html>
