<?php
// modules/sales/list_sales.php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_role = $_SESSION['user']['role'] ?? 'cashier';

if ($shop_id == 0) {
    die("Shop session missing.");
}

// Get default date range (last 30 days)
$default_from = date('Y-m-d', strtotime('-30 days'));
$default_to = date('Y-m-d');

// Get total stats for dashboard
$stats_sql = "SELECT 
                COUNT(DISTINCT s.id) as total_sales,
                SUM(s.total) as total_revenue,
                SUM(s.paid) as total_paid,
                AVG(s.total) as avg_sale,
                COUNT(DISTINCT s.customer_id) as total_customers
              FROM sales s
              WHERE s.shop_id = ?
              AND DATE(s.sale_date) BETWEEN ? AND ?";
$stats_stmt = $pdo->prepare($stats_sql);
$stats_stmt->execute([$shop_id, $default_from, $default_to]);
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
?>

<style>
/* Sales list page specific styles */
.main-content-wrapper {
    padding: 20px;
    min-height: calc(100vh - 80px);
    background-color: #f5f7fb;
}

.card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transition: transform 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}

.card-header {
    border-radius: 12px 12px 0 0 !important;
}

.breadcrumb {
    background: transparent;
    padding: 0;
    margin-bottom: 1rem;
}
.breadcrumb-item a {
    color: #6c757d;
    text-decoration: none;
}
.breadcrumb-item.active {
    color: #28a745;
    font-weight: bold;
}
.table th {
    font-weight: 600;
    white-space: nowrap;
}

.status-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
}
.status-paid { background: #28a745; color: white; }
.status-open { background: #ffc107; color: #212529; }
.status-partially_paid { background: #17a2b8; color: white; }
.status-cancelled { background: #dc3545; color: white; }

.payment-badge {
    padding: 3px 6px;
    border-radius: 3px;
    font-size: 11px;
    font-weight: 600;
    background: #6c757d;
    color: white;
}
.payment-CASH { background: #28a745; }
.payment-M-PESA { background: #007bff; }
.payment-TIGO-PESA { background: #6f42c1; }
.payment-AIRTEL-MONEY { background: #fd7e14; }
.payment-CARD { background: #17a2b8; }

.action-btn {
    padding: 4px 8px;
    font-size: 12px;
    margin: 0 2px;
    transition: all 0.2s;
}

.action-btn:hover {
    transform: scale(1.1);
}

.table-hover tbody tr:hover {
    background-color: rgba(0,0,0,.075);
}

.btn-primary {
    background: linear-gradient(135deg, #007bff, #6610f2);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
}

.btn-success {
    background: linear-gradient(135deg, #28a745, #20c997);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.btn-outline-secondary {
    border-radius: 8px;
    padding: 8px 16px;
    transition: all 0.3s ease;
}

.btn-outline-secondary:hover {
    transform: translateY(-2px);
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .main-content-wrapper {
        padding: 15px 10px;
    }
    
    .card {
        margin-bottom: 15px;
    }
    
    .d-flex.justify-content-between {
        flex-direction: column;
        gap: 15px;
    }
    
    .btn-group {
        width: 100%;
    }
    
    .table-responsive {
        font-size: 14px;
    }
    
    .card-footer .row {
        flex-direction: column;
        gap: 15px;
        text-align: center;
    }
    
    .card-footer .float-right {
        float: none !important;
        justify-content: center;
    }
    
    .action-btn {
        padding: 3px 6px;
        margin: 1px;
    }
}

/* Loading animation */
.spinner-border {
    width: 3rem;
    height: 3rem;
}

/* Modal styles */
.modal-lg {
    max-width: 900px;
}

/* Custom notification styles */
.notification {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    min-width: 300px;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    animation: slideIn 0.3s ease;
}

@keyframes slideIn {
    from { transform: translateX(100%); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}

@keyframes slideOut {
    from { transform: translateX(0); opacity: 1; }
    to { transform: translateX(100%); opacity: 0; }
}

.notification.hide {
    animation: slideOut 0.3s ease forwards;
}

.notification-success {
    border-left: 5px solid #28a745;
}

.notification-error {
    border-left: 5px solid #dc3545;
}

.notification-warning {
    border-left: 5px solid #ffc107;
}

.notification-info {
    border-left: 5px solid #17a2b8;
}

.notification-header {
    padding: 12px 15px;
    display: flex;
    align-items: center;
    color: white;
}

.notification-success .notification-header {
    background: linear-gradient(135deg, #28a745, #20c997);
}

.notification-error .notification-header {
    background: linear-gradient(135deg, #dc3545, #e83e8c);
}

.notification-warning .notification-header {
    background: linear-gradient(135deg, #ffc107, #fd7e14);
}

.notification-info .notification-header {
    background: linear-gradient(135deg, #17a2b8, #007bff);
}

.notification-body {
    padding: 15px;
    background: white;
}

.notification-icon {
    margin-right: 10px;
    font-size: 18px;
}

.notification-title {
    font-weight: 600;
    font-size: 16px;
    margin: 0;
}

.notification-message {
    margin: 0;
    line-height: 1.5;
}

.notification-close {
    margin-left: auto;
    background: none;
    border: none;
    color: white;
    font-size: 18px;
    cursor: pointer;
    opacity: 0.8;
    transition: opacity 0.2s;
}

.notification-close:hover {
    opacity: 1;
}

/* Progress bar for operations */
.progress-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    width: 350px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    overflow: hidden;
    animation: slideIn 0.3s ease;
}

.progress-header {
    padding: 15px;
    background: linear-gradient(135deg, #007bff, #6610f2);
    color: white;
    display: flex;
    align-items: center;
}

.progress-icon {
    margin-right: 10px;
    font-size: 20px;
}

.progress-title {
    font-weight: 600;
    font-size: 16px;
    margin: 0;
    flex-grow: 1;
}

.progress-body {
    padding: 20px;
}

.progress-text {
    margin-bottom: 10px;
    color: #666;
}

.progress-bar {
    height: 8px;
    background: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #28a745, #20c997);
    border-radius: 4px;
    transition: width 0.3s ease;
    width: 0%;
}

/* Confirmation dialog styles */
.confirmation-dialog {
    background: white;
    border-radius: 15px;
    padding: 0;
    overflow: hidden;
    max-width: 450px;
    margin: 20px auto;
}

.confirmation-header {
    padding: 25px 30px 15px;
    text-align: center;
    background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}

.confirmation-icon {
    font-size: 60px;
    margin-bottom: 15px;
}

.confirmation-icon.warning {
    color: #ffc107;
}

.confirmation-icon.danger {
    color: #dc3545;
}

.confirmation-icon.success {
    color: #28a745;
}

.confirmation-title {
    font-size: 22px;
    font-weight: 600;
    margin-bottom: 10px;
    color: #333;
}

.confirmation-message {
    color: #666;
    line-height: 1.6;
    font-size: 15px;
}

.confirmation-body {
    padding: 20px 30px;
    text-align: center;
}

.confirmation-details {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin: 15px 0;
    text-align: left;
}

.confirmation-footer {
    padding: 20px 30px;
    background: #f8f9fa;
    display: flex;
    justify-content: center;
    gap: 10px;
}

.confirmation-btn {
    min-width: 120px;
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s;
    border: none;
    cursor: pointer;
}

.confirmation-btn.cancel {
    background: #6c757d;
    color: white;
}

.confirmation-btn.cancel:hover {
    background: #5a6268;
    transform: translateY(-2px);
}

.confirmation-btn.confirm {
    background: linear-gradient(135deg, #dc3545, #e83e8c);
    color: white;
}

.confirmation-btn.confirm:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
}

.confirmation-btn.success {
    background: linear-gradient(135deg, #28a745, #20c997);
    color: white;
}

.confirmation-btn.success:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}
</style>

<!-- MAIN CONTENT WRAPPER - This will shift when sidebar collapses -->
<div class="main-content-wrapper" id="mainContent">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="text-success mb-0">
                    <i class="fas fa-chart-line"></i> Sales Management
                </h3>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb bg-transparent p-0">
                        <li class="breadcrumb-item"><a href="../dashboard.php">Dashboard</a></li>
                        <li class="breadcrumb-item active">Sales</li>
                    </ol>
                </nav>
            </div>
            <div>
                <a href="pos.php" class="btn btn-primary">
                    <i class="fas fa-cash-register"></i> New Sale
                </a>
                <button type="button" class="btn btn-success" onclick="printSalesReport()">
                    <i class="fas fa-print"></i> Print Report
                </button>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card bg-info text-white">
                    <div class="card-body text-center p-3">
                        <h6 class="card-title mb-1">Total Sales</h6>
                        <h3 class="mb-0"><?= number_format($stats['total_sales'] ?? 0) ?></h3>
                        <small>Transactions</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center p-3">
                        <h6 class="card-title mb-1">Total Revenue</h6>
                        <h4 class="mb-0">TZS <?= number_format($stats['total_revenue'] ?? 0, 2) ?></h4>
                        <small>Gross Amount</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center p-3">
                        <h6 class="card-title mb-1">Total Collected</h6>
                        <h4 class="mb-0">TZS <?= number_format($stats['total_paid'] ?? 0, 2) ?></h4>
                        <small>Amount Paid</small>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-warning">
                    <div class="card-body text-center p-3">
                        <h6 class="card-title mb-1">Avg. Sale</h6>
                        <h4 class="mb-0">TZS <?= number_format($stats['avg_sale'] ?? 0, 2) ?></h4>
                        <small>Per Transaction</small>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-secondary text-white">
                    <div class="card-body text-center p-3">
                        <h6 class="card-title mb-1">Customers</h6>
                        <h3 class="mb-0"><?= number_format($stats['total_customers'] ?? 0) ?></h3>
                        <small>Unique</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Card -->
        <div class="card mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Sales</h5>
            </div>
            <div class="card-body">
                <form id="filterForm" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">From Date</label>
                        <input type="date" name="from_date" class="form-control" 
                               value="<?= $default_from ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">To Date</label>
                        <input type="date" name="to_date" class="form-control" 
                               value="<?= $default_to ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="">All Status</option>
                            <option value="paid">Paid</option>
                            <option value="open">Open</option>
                            <option value="partially_paid">Partially Paid</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <option value="">All Methods</option>
                            <option value="CASH">Cash</option>
                            <option value="M-PESA">M-PESA</option>
                            <option value="TIGO-PESA">Tigo Pesa</option>
                            <option value="AIRTEL-MONEY">Airtel Money</option>
                            <option value="CARD">Card</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-search"></i> Filter
                            </button>
                        </div>
                    </div>
                </form>
                
                <!-- Quick Date Filters -->
                <div class="row mt-3">
                    <div class="col-md-12">
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('today')">
                                Today
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('yesterday')">
                                Yesterday
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('this_week')">
                                This Week
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('this_month')">
                                This Month
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('last_month')">
                                Last Month
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sales Table -->
        <div class="card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-list"></i> Sales List</h5>
                <div class="d-flex align-items-center">
                    <div class="input-group input-group-sm mr-3" style="width: 200px;">
                        <input type="text" id="searchInput" class="form-control" placeholder="Search sales...">
                        <div class="input-group-append">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-sm btn-outline-success" onclick="exportToCSV()">
                            <i class="fas fa-file-csv"></i> Export CSV
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="printSalesReport()">
                            <i class="fas fa-print"></i> Print Report
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-info" onclick="exportToPDF()">
                            <i class="fas fa-file-pdf"></i> Export PDF
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover mb-0" id="salesTable">
                        <thead class="thead-dark">
                            <tr>
                                <th width="50">ID</th>
                                <th width="120">Invoice No</th>
                                <th width="150">Date & Time</th>
                                <th>Customer</th>
                                <th width="80">Items</th>
                                <th width="100">Total</th>
                                <th width="100">Paid</th>
                                <th width="100">Due</th>
                                <th width="100">Payment</th>
                                <th width="90">Status</th>
                                <th width="130" class="no-print">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="salesBody">
                            <tr>
                                <td colspan="11" class="text-center py-4">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="sr-only">Loading...</span>
                                    </div>
                                    <p class="mt-2">Loading sales data...</p>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot class="bg-light" id="salesFoot">
                            <tr>
                                <td colspan="5" class="text-right font-weight-bold">TOTALS:</td>
                                <td class="font-weight-bold text-success" id="totalSales">0.00</td>
                                <td class="font-weight-bold text-primary" id="totalPaid">0.00</td>
                                <td class="font-weight-bold text-danger" id="totalDue">0.00</td>
                                <td colspan="3"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
            <div class="card-footer">
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center">
                            <span class="mr-3">Show:</span>
                            <select id="rowsPerPage" class="form-control form-control-sm" style="width: 80px;">
                                <option value="10">10</option>
                                <option value="25" selected>25</option>
                                <option value="50">50</option>
                                <option value="100">100</option>
                            </select>
                            <span class="ml-3">rows per page</span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <nav aria-label="Page navigation" class="float-right">
                            <ul class="pagination pagination-sm mb-0" id="pagination">
                                <!-- Pagination will be added dynamically -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Sale Modal -->
<div class="modal fade" id="viewSaleModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-file-invoice"></i> Sale Details</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" id="saleDetails" style="max-height: 70vh; overflow-y: auto;">
                <!-- Sale details will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times"></i> Close
                </button>
                <button type="button" class="btn btn-primary" id="modalPrintBtn" style="display: none;">
                    <i class="fas fa-print"></i> Print Receipt
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Confirmation Dialog Template -->
<div id="confirmationDialog" style="display: none;">
    <div class="confirmation-dialog">
        <div class="confirmation-header">
            <div class="confirmation-icon warning">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <h4 class="confirmation-title" id="confirmTitle">Confirm Action</h4>
            <p class="confirmation-message" id="confirmMessage">Are you sure you want to proceed?</p>
        </div>
        <div class="confirmation-body">
            <div class="confirmation-details" id="confirmDetails" style="display: none;">
                <small><strong>Details:</strong> <span id="detailsText"></span></small>
            </div>
        </div>
        <div class="confirmation-footer">
            <button class="confirmation-btn cancel" onclick="window.confirmCallback(false)">
                <i class="fas fa-times"></i> Cancel
            </button>
            <button class="confirmation-btn confirm" onclick="window.confirmCallback(true)">
                <i class="fas fa-check"></i> Confirm
            </button>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>

<script>
// Global variables
let currentPage = 1;
let totalPages = 1;
let currentSaleId = null;

// Notification system
class NotificationSystem {
    static showSuccess(message, title = 'Success') {
        this.showNotification('success', title, message);
    }
    
    static showError(message, title = 'Error') {
        this.showNotification('error', title, message);
    }
    
    static showWarning(message, title = 'Warning') {
        this.showNotification('warning', title, message);
    }
    
    static showInfo(message, title = 'Information') {
        this.showNotification('info', title, message);
    }
    
    static showNotification(type, title, message) {
        const icons = {
            success: 'fas fa-check-circle',
            error: 'fas fa-exclamation-circle',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };
        
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-header">
                <i class="notification-icon ${icons[type]}"></i>
                <h6 class="notification-title">${title}</h6>
                <button class="notification-close" onclick="this.parentElement.parentElement.classList.add('hide')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="notification-body">
                <p class="notification-message">${message}</p>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.classList.add('hide');
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }
        }, 5000);
    }
    
    static showProgress(message, title = 'Processing...') {
        const progress = document.createElement('div');
        progress.className = 'progress-notification';
        progress.id = 'progressNotification';
        progress.innerHTML = `
            <div class="progress-header">
                <i class="progress-icon fas fa-spinner fa-spin"></i>
                <h6 class="progress-title">${title}</h6>
            </div>
            <div class="progress-body">
                <p class="progress-text">${message}</p>
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
            </div>
        `;
        
        document.body.appendChild(progress);
        return {
            update: (percent, message) => {
                const fill = document.getElementById('progressFill');
                const text = progress.querySelector('.progress-text');
                if (fill) fill.style.width = `${percent}%`;
                if (text && message) text.textContent = message;
            },
            close: () => {
                if (progress.parentNode) {
                    progress.parentNode.removeChild(progress);
                }
            }
        };
    }
}

// Confirmation dialog system
class ConfirmationDialog {
    static show(options) {
        return new Promise((resolve) => {
            const dialog = document.createElement('div');
            dialog.className = 'confirmation-overlay';
            dialog.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 99999;
                display: flex;
                align-items: center;
                justify-content: center;
                animation: fadeIn 0.3s;
            `;
            
            // Custom icon based on type
            let iconClass = 'fas fa-exclamation-triangle';
            let iconColor = 'warning';
            if (options.type === 'danger') {
                iconClass = 'fas fa-exclamation-circle';
                iconColor = 'danger';
            } else if (options.type === 'success') {
                iconClass = 'fas fa-check-circle';
                iconColor = 'success';
            }
            
            dialog.innerHTML = `
                <div class="confirmation-dialog" style="animation: scaleIn 0.3s;">
                    <div class="confirmation-header">
                        <div class="confirmation-icon ${iconColor}">
                            <i class="${iconClass}"></i>
                        </div>
                        <h4 class="confirmation-title">${options.title}</h4>
                        <p class="confirmation-message">${options.message}</p>
                    </div>
                    ${options.details ? `
                    <div class="confirmation-body">
                        <div class="confirmation-details">
                            <small><strong>Details:</strong> ${options.details}</small>
                        </div>
                    </div>
                    ` : ''}
                    <div class="confirmation-footer">
                        <button class="confirmation-btn cancel" id="cancelBtn">
                            <i class="fas fa-times"></i> ${options.cancelText || 'Cancel'}
                        </button>
                        <button class="confirmation-btn ${options.type || 'confirm'}" id="confirmBtn">
                            <i class="fas fa-check"></i> ${options.confirmText || 'Confirm'}
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(dialog);
            
            // Add styles for animations
            const style = document.createElement('style');
            style.textContent = `
                @keyframes fadeIn {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                @keyframes scaleIn {
                    from { transform: scale(0.9); opacity: 0; }
                    to { transform: scale(1); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
            
            // Handle button clicks
            dialog.querySelector('#cancelBtn').onclick = () => {
                document.body.removeChild(dialog);
                document.head.removeChild(style);
                resolve(false);
            };
            
            dialog.querySelector('#confirmBtn').onclick = () => {
                document.body.removeChild(dialog);
                document.head.removeChild(style);
                resolve(true);
            };
            
            // Close on ESC key
            const handleEsc = (e) => {
                if (e.key === 'Escape') {
                    document.body.removeChild(dialog);
                    document.head.removeChild(style);
                    document.removeEventListener('keydown', handleEsc);
                    resolve(false);
                }
            };
            document.addEventListener('keydown', handleEsc);
        });
    }
}

$(document).ready(function() {
    console.log('Sales page loaded');
    
    // Load initial data
    loadSales();
    
    // Filter form submission
    $('#filterForm').on('submit', function(e) {
        e.preventDefault();
        NotificationSystem.showInfo('Applying filters...', 'Filtering');
        loadSales();
    });
    
    // Rows per page change
    $('#rowsPerPage').change(function() {
        NotificationSystem.showInfo('Changing rows per page...');
        loadSales();
    });
    
    // Search functionality with debounce
    let searchTimeout;
    $('#searchInput').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            if (searchTerm.length >= 2 || searchTerm.length === 0) {
                loadSales();
            }
        }, 500);
    });
});

function loadSales(page = 1) {
    currentPage = page;
    
    const formData = new FormData(document.getElementById('filterForm'));
    formData.append('page', page);
    formData.append('rows_per_page', $('#rowsPerPage').val());
    formData.append('search', $('#searchInput').val());
    
    $('#salesBody').html(`
        <tr>
            <td colspan="11" class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-2">Loading sales data...</p>
            </td>
        </tr>
    `);
    
    $.ajax({
        url: 'ajax_load_sales.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response && response.status === 'success') {
                $('#salesBody').html(response.html);
                $('#totalSales').text('TZS ' + (response.totals?.total_sales?.toFixed(2) || '0.00'));
                $('#totalPaid').text('TZS ' + (response.totals?.total_paid?.toFixed(2) || '0.00'));
                $('#totalDue').text('TZS ' + (response.totals?.total_due?.toFixed(2) || '0.00'));
                
                totalPages = response.pagination?.total_pages || 1;
                updatePagination();
                
                NotificationSystem.showSuccess(`Loaded ${response.pagination?.total_rows || 0} sales`, 'Data Loaded');
            } else {
                let errorMsg = response?.message || 'Unknown error from server';
                $('#salesBody').html(`
                    <tr>
                        <td colspan="11" class="text-center text-danger py-4">
                            <i class="fas fa-exclamation-circle fa-2x mb-2"></i>
                            <p>${errorMsg}</p>
                        </td>
                    </tr>
                `);
                NotificationSystem.showError(errorMsg, 'Load Failed');
            }
        },
        error: function(xhr, status, error) {
            $('#salesBody').html(`
                <tr>
                    <td colspan="11" class="text-center text-danger py-4">
                        <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                        <p>Failed to load sales data</p>
                        <small class="text-muted">Error: ${status} - ${error}</small>
                        <br>
                        <button class="btn btn-sm btn-primary mt-2" onclick="loadSales()">
                            <i class="fas fa-redo"></i> Retry
                        </button>
                    </td>
                </tr>
            `);
            NotificationSystem.showError(`Failed to load: ${error}`, 'Connection Error');
        }
    });
}

function updatePagination() {
    const pagination = $('#pagination');
    pagination.empty();
    
    if (totalPages <= 1) return;
    
    // Previous button
    const prevDisabled = currentPage === 1 ? 'disabled' : '';
    pagination.append(`
        <li class="page-item ${prevDisabled}">
            <a class="page-link" href="#" onclick="loadSales(${currentPage - 1}); return false;">
                &laquo;
            </a>
        </li>
    `);
    
    // Page numbers (show only 5 pages around current)
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const active = i === currentPage ? 'active' : '';
        pagination.append(`
            <li class="page-item ${active}">
                <a class="page-link" href="#" onclick="loadSales(${i}); return false;">${i}</a>
            </li>
        `);
    }
    
    // Next button
    const nextDisabled = currentPage === totalPages ? 'disabled' : '';
    pagination.append(`
        <li class="page-item ${nextDisabled}">
            <a class="page-link" href="#" onclick="loadSales(${currentPage + 1}); return false;">
                &raquo;
            </a>
        </li>
    `);
}

function setDateRange(range) {
    const today = new Date();
    let fromDate, toDate;
    
    switch(range) {
        case 'today':
            fromDate = toDate = today.toISOString().split('T')[0];
            break;
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            fromDate = toDate = yesterday.toISOString().split('T')[0];
            break;
        case 'this_week':
            const firstDay = new Date(today);
            firstDay.setDate(today.getDate() - today.getDay());
            fromDate = firstDay.toISOString().split('T')[0];
            toDate = today.toISOString().split('T')[0];
            break;
        case 'this_month':
            fromDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
            toDate = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0];
            break;
        case 'last_month':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            fromDate = lastMonth.toISOString().split('T')[0];
            toDate = new Date(today.getFullYear(), today.getMonth(), 0).toISOString().split('T')[0];
            break;
    }
    
    $('input[name="from_date"]').val(fromDate);
    $('input[name="to_date"]').val(toDate);
    NotificationSystem.showInfo(`Date range set to: ${fromDate} - ${toDate}`);
    loadSales(1);
}

// ==================== SALE ACTIONS ====================

function viewSale(saleId) {
    console.log('Opening view modal for sale ID:', saleId);
    currentSaleId = saleId;
    
    $('#saleDetails').html(`
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="sr-only">Loading...</span>
            </div>
            <p class="mt-3">Loading sale details...</p>
        </div>
    `);
    
    $('#viewSaleModal').modal('show');
    
    $.ajax({
        url: 'ajax_view_sale.php',
        type: 'GET',
        data: { id: saleId },
        success: function(response) {
            $('#saleDetails').html(response);
            $('#modalPrintBtn').show().off('click').on('click', function() {
                printReceipt(saleId);
            });
            NotificationSystem.showSuccess('Sale details loaded');
        },
        error: function(xhr, status, error) {
            $('#saleDetails').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <h5>Failed to load sale details</h5>
                    <p>Error: ${error}</p>
                    <button class="btn btn-sm btn-primary mt-2" onclick="viewSale(${saleId})">
                        <i class="fas fa-redo"></i> Try Again
                    </button>
                </div>
            `);
            NotificationSystem.showError(`Failed to load details: ${error}`);
        }
    });
}

function printReceipt(saleId) {
    NotificationSystem.showInfo('Opening receipt for printing...', 'Print');
    window.open(`print_sale_receipt.php?id=${saleId}`, '_blank');
}

async function deleteSale(saleId, invoiceNo) {
    const confirmed = await ConfirmationDialog.show({
        title: 'Cancel Sale?',
        message: 'Are you sure you want to cancel this sale?',
        details: `Invoice: ${invoiceNo}<br>This action cannot be undone.`,
        type: 'danger',
        confirmText: 'Yes, Cancel Sale',
        cancelText: 'No, Keep It'
    });
    
    if (!confirmed) {
        NotificationSystem.showInfo('Sale cancellation cancelled', 'Cancelled');
        return;
    }
    
    // Show progress
    const progress = NotificationSystem.showProgress('Cancelling sale and returning stock...', 'Processing');
    
    try {
        const response = await $.ajax({
            url: 'ajax_delete_sale.php',
            type: 'POST',
            data: { 
                id: saleId,
                confirm: 'yes'
            },
            dataType: 'json'
        });
        
        progress.update(100, 'Complete!');
        setTimeout(() => progress.close(), 500);
        
        if (response.status === 'success') {
            NotificationSystem.showSuccess(response.message, 'Sale Cancelled');
            setTimeout(() => {
                loadSales(currentPage);
            }, 1500);
        } else {
            NotificationSystem.showError(response.message || 'Failed to cancel sale', 'Error');
        }
    } catch (error) {
        progress.close();
        NotificationSystem.showError('Server error: ' + error.statusText, 'Error');
    }
}

// ==================== EXPORT FUNCTIONS ====================

function exportToCSV() {
    ConfirmationDialog.show({
        title: 'Export to CSV',
        message: 'Export sales data to CSV file?',
        details: 'This will download all filtered sales data in CSV format.',
        type: 'success',
        confirmText: 'Export Now',
        cancelText: 'Cancel Export'
    }).then(async (confirmed) => {
        if (!confirmed) {
            NotificationSystem.showInfo('CSV export cancelled', 'Export Cancelled');
            return;
        }
        
        const progress = NotificationSystem.showProgress('Preparing CSV file...', 'Exporting');
        
        // Get form data
        const form = document.getElementById('filterForm');
        const formData = new FormData(form);
        
        // Convert to URL parameters
        const params = new URLSearchParams();
        for (let [key, value] of formData.entries()) {
            if (value) params.append(key, value);
        }
        
        // Update progress
        progress.update(30, 'Collecting data...');
        
        // Simple direct download approach
        const url = `ajax_export_sales.php?${params.toString()}`;
        
        // Create temporary iframe for download
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);
        
        progress.update(70, 'Generating file...');
        
        // Check if download started
        setTimeout(() => {
            progress.update(100, 'Download ready!');
            setTimeout(() => {
                progress.close();
                NotificationSystem.showSuccess('CSV export started. Check your downloads folder.', 'Export Started');
            }, 500);
        }, 2000);
        
        // Clean up
        setTimeout(() => {
            if (iframe.parentNode) {
                iframe.parentNode.removeChild(iframe);
            }
        }, 10000);
    });
}

function exportToPDF() {
    ConfirmationDialog.show({
        title: 'Export to PDF',
        message: 'Open sales report for PDF export?',
        details: 'This will open the printable report. Use your browser\'s "Print to PDF" feature.',
        type: 'info',
        confirmText: 'Open Report',
        cancelText: 'Cancel'
    }).then((confirmed) => {
        if (!confirmed) {
            NotificationSystem.showInfo('PDF export cancelled', 'Export Cancelled');
            return;
        }
        
        // Get form data
        const form = document.getElementById('filterForm');
        const formData = new FormData(form);
        
        // Convert to URL parameters
        const params = new URLSearchParams();
        for (let [key, value] of formData.entries()) {
            if (value) params.append(key, value);
        }
        
        // Open print report, user can then print as PDF
        const url = `print_sales_report.php?${params.toString()}`;
        window.open(url, '_blank');
        
        NotificationSystem.showInfo('Report opened. Use "Print to PDF" in your browser.', 'PDF Export');
    });
}

function printSalesReport() {
    ConfirmationDialog.show({
        title: 'Print Report',
        message: 'Open sales report for printing?',
        details: 'This will open a printable version of the sales report.',
        type: 'info',
        confirmText: 'Open Report',
        cancelText: 'Cancel'
    }).then((confirmed) => {
        if (!confirmed) {
            NotificationSystem.showInfo('Print cancelled', 'Print Cancelled');
            return;
        }
        
        // Get form data
        const form = document.getElementById('filterForm');
        const formData = new FormData(form);
        
        // Convert to URL parameters
        const params = new URLSearchParams();
        for (let [key, value] of formData.entries()) {
            if (value) params.append(key, value);
        }
        
        const url = `print_sales_report.php?${params.toString()}`;
        window.open(url, '_blank');
        
        NotificationSystem.showInfo('Report opened for printing.', 'Print Report');
    });
}

// ==================== UTILITY FUNCTIONS ====================

// Placeholder function for edit (if needed)
async function editSale(saleId) {
    const confirmed = await ConfirmationDialog.show({
        title: 'Edit Sale',
        message: 'Edit this sale?',
        details: 'This will open the sale for editing.',
        type: 'warning',
        confirmText: 'Edit Sale',
        cancelText: 'Cancel'
    });
    
    if (confirmed) {
        NotificationSystem.showInfo('Redirecting to edit page...', 'Edit');
        // Redirect to edit page
        window.location.href = `edit_sale.php?id=${saleId}`;
    } else {
        NotificationSystem.showInfo('Edit cancelled', 'Cancelled');
    }
}

// Add payment to sale
async function addPayment(saleId, invoiceNo) {
    const confirmed = await ConfirmationDialog.show({
        title: 'Add Payment',
        message: 'Add payment to this sale?',
        details: `Invoice: ${invoiceNo}<br>This will open the payment form.`,
        type: 'success',
        confirmText: 'Add Payment',
        cancelText: 'Cancel'
    });
    
    if (confirmed) {
        // Implement payment modal here
        NotificationSystem.showInfo('Payment feature coming soon!', 'Info');
    } else {
        NotificationSystem.showInfo('Payment addition cancelled', 'Cancelled');
    }
}

// Quick actions
function quickActions(saleId, invoiceNo) {
    // Show quick actions menu
    const actions = `
        <div style="position: absolute; background: white; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); z-index: 1000; padding: 10px; min-width: 200px;">
            <button class="btn btn-sm btn-block btn-info mb-2" onclick="viewSale(${saleId})">
                <i class="fas fa-eye"></i> View Details
            </button>
            <button class="btn btn-sm btn-block btn-primary mb-2" onclick="printReceipt(${saleId})">
                <i class="fas fa-print"></i> Print Receipt
            </button>
            <button class="btn btn-sm btn-block btn-warning mb-2" onclick="addPayment(${saleId}, '${invoiceNo}')">
                <i class="fas fa-money-bill-wave"></i> Add Payment
            </button>
            <button class="btn btn-sm btn-block btn-danger" onclick="deleteSale(${saleId}, '${invoiceNo}')">
                <i class="fas fa-trash"></i> Cancel Sale
            </button>
        </div>
    `;
    
    // Create and show menu
    const menu = document.createElement('div');
    menu.innerHTML = actions;
    menu.style.position = 'fixed';
    menu.style.top = '50%';
    menu.style.left = '50%';
    menu.style.transform = 'translate(-50%, -50%)';
    menu.style.zIndex = '9999';
    
    // Add overlay
    const overlay = document.createElement('div');
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100%';
    overlay.style.height = '100%';
    overlay.style.background = 'rgba(0,0,0,0.5)';
    overlay.style.zIndex = '9998';
    
    overlay.onclick = function() {
        document.body.removeChild(overlay);
        document.body.removeChild(menu);
    };
    
    document.body.appendChild(overlay);
    document.body.appendChild(menu);
}
</script>