<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Sales History - WITH DELETE BUTTON
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/pos/sales/index.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/pos/sales/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.php';
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Handle delete action
if (isset($_GET['delete']) && isset($_GET['id']) && is_numeric($_GET['id'])) {
    $sale_id = (int)$_GET['id'];
    
    // Store current GET parameters for redirect (excluding delete and id)
    $redirect_params = $_GET;
    unset($redirect_params['delete']);
    unset($redirect_params['id']);
    $redirect_query = http_build_query($redirect_params);
    
    try {
        // First, check if sale exists and get its status
        $sale = db_fetch_one("SELECT payment_status, total_amount FROM pos_sales WHERE sale_id = ?", [$sale_id]);
        
        if (!$sale) {
            throw new Exception("Sale not found");
        }
        
        // Only allow deletion of voided or refunded sales, or sales with no items
        if (!in_array($sale['payment_status'], ['voided', 'refunded'])) {
            // Check if sale has items
            $item_count = db_fetch_value("SELECT COUNT(*) FROM pos_sale_items WHERE sale_id = ?", [$sale_id]);
            
            if ($item_count > 0) {
                // Sale has items but is not voided/refunded - ask to void first
                $message = "This sale must be voided before deletion. Please void the transaction first.";
                $type = 'warning';
                
                if (function_exists('set_flash_message')) {
                    set_flash_message($message, $type);
                } else {
                    session_start();
                    $_SESSION['flash_message'] = $message;
                    $_SESSION['flash_type'] = $type;
                }
                
                header('Location: index.php' . ($redirect_query ? '?' . $redirect_query : ''));
                exit;
            }
        }
        
        // Begin transaction
        db_begin_transaction();
        
        // Delete related records first (sale items)
        db_execute("DELETE FROM pos_sale_items WHERE sale_id = ?", [$sale_id]);
        
        // Delete payments if they exist
        if (db_table_exists('pos_payments')) {
            db_execute("DELETE FROM pos_payments WHERE sale_id = ?", [$sale_id]);
        }
        
        // Delete the sale
        db_execute("DELETE FROM pos_sales WHERE sale_id = ?", [$sale_id]);
        
        // Commit transaction
        db_commit();
        
        $message = "Sale #" . $sale_id . " deleted successfully.";
        $type = 'success';
        
        // Log the action
        error_log("Sale ID $sale_id deleted by user " . ($current_user['user_id'] ?? 'unknown'));
        
    } catch (Exception $e) {
        // Rollback transaction
        db_rollback();
        
        error_log("Error deleting sale: " . $e->getMessage());
        $message = "Error deleting sale: " . $e->getMessage();
        $type = 'danger';
    }
    
    // Set flash message
    if (function_exists('set_flash_message')) {
        set_flash_message($message, $type);
    } else {
        session_start();
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_type'] = $type;
    }
    
    // Redirect back to sales list
    header('Location: index.php' . ($redirect_query ? '?' . $redirect_query : ''));
    exit;
}

// Define helper functions if they don't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

if (!function_exists('format_datetime')) {
    function format_datetime($datetime) {
        if (empty($datetime)) return '';
        return date('d/m/Y H:i', strtotime($datetime));
    }
}

if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) {
            return $diff . ' seconds ago';
        } elseif ($diff < 3600) {
            $mins = floor($diff / 60);
            return $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 2592000) {
            $days = floor($diff / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } else {
            return date('M d, Y', $time);
        }
    }
}

if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

if (!function_exists('display_flash_messages')) {
    function display_flash_messages() {
        if (isset($_SESSION['flash_messages']) && !empty($_SESSION['flash_messages'])) {
            foreach ($_SESSION['flash_messages'] as $flash) {
                $type = $flash['type'] ?? 'info';
                $message = $flash['message'] ?? '';
                echo '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">';
                echo htmlspecialchars($message);
                echo '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
                echo '</div>';
            }
            $_SESSION['flash_messages'] = [];
        }
    }
}

if (!function_exists('db_table_exists')) {
    function db_table_exists($table_name) {
        try {
            $result = db_query("SHOW TABLES LIKE '$table_name'");
            return $result && $result->rowCount() > 0;
        } catch (Exception $e) {
            return false;
        }
    }
}

if (!function_exists('db_begin_transaction')) {
    function db_begin_transaction() {
        global $db;
        if (isset($db) && $db instanceof PDO) {
            $db->beginTransaction();
        }
    }
}

if (!function_exists('db_commit')) {
    function db_commit() {
        global $db;
        if (isset($db) && $db instanceof PDO) {
            $db->commit();
        }
    }
}

if (!function_exists('db_rollback')) {
    function db_rollback() {
        global $db;
        if (isset($db) && $db instanceof PDO) {
            $db->rollBack();
        }
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('pos.sales.view');
// }

// Set page title
$page_title = 'POS Sales History';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$outlet_id = isset($_GET['outlet_id']) && $_GET['outlet_id'] !== '' ? (int)$_GET['outlet_id'] : null;
$cashier_id = isset($_GET['cashier_id']) && $_GET['cashier_id'] !== '' ? (int)$_GET['cashier_id'] : null;
$status = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$sort = $_GET['sort'] ?? 'sale_time';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE : 25;

// Build where clause
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (s.receipt_number LIKE ? OR s.customer_name LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
}

if ($outlet_id) {
    $where .= " AND s.outlet_id = ?";
    $params[] = $outlet_id;
}

if ($cashier_id) {
    $where .= " AND s.user_id = ?";
    $params[] = $cashier_id;
}

if (!empty($status)) {
    $where .= " AND s.payment_status = ?";
    $params[] = $status;
}

if (!empty($date_from)) {
    $where .= " AND DATE(s.sale_time) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where .= " AND DATE(s.sale_time) <= ?";
    $params[] = $date_to;
}

// Validate sort column
$allowed_sort = ['sale_id', 'receipt_number', 'sale_time', 'total_amount', 'payment_status'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'sale_time';
}

// Get total count
$total = 0;
try {
    $count_sql = "SELECT COUNT(*) FROM pos_sales s WHERE $where";
    $total = (int)db_fetch_value($count_sql, $params) ?: 0;
} catch (Exception $e) {
    error_log("Error counting sales: " . $e->getMessage());
}

// Get sales with details
$sales = [];
try {
    $sql = "
        SELECT 
            s.*,
            o.outlet_name,
            u.first_name, u.last_name,
            (SELECT COUNT(*) FROM pos_sale_items WHERE sale_id = s.sale_id) as item_count
        FROM pos_sales s
        JOIN pos_outlets o ON s.outlet_id = o.outlet_id
        JOIN users u ON s.user_id = u.user_id
        WHERE $where
        ORDER BY $sort $order
    ";
    
    // Get paginated data
    $offset = ($page - 1) * $per_page;
    $data_sql = $sql . " LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
    $sales = db_fetch_all($data_sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching sales: " . $e->getMessage());
}

// Calculate pagination
$total_pages = $per_page > 0 ? ceil($total / $per_page) : 1;

// Get outlets for filter
$outlets = [];
try {
    $outlets = db_fetch_all("SELECT outlet_id, outlet_name FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching outlets: " . $e->getMessage());
}

// Get cashiers for filter
$cashiers = [];
try {
    $cashiers = db_fetch_all("
        SELECT DISTINCT u.user_id, u.first_name, u.last_name
        FROM pos_sales s
        JOIN users u ON s.user_id = u.user_id
        ORDER BY u.first_name
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching cashiers: " . $e->getMessage());
}

// Get summary statistics - FIXED REVENUE CALCULATION
$stats = [
    'total_sales' => $total,
    'total_revenue' => 0,
    'avg_sale' => 0,
    'total_items' => 0
];

try {
    // Get total revenue from all sales matching the filters
    $revenue_sql = "SELECT COALESCE(SUM(total_amount), 0) as total FROM pos_sales s WHERE $where";
    $stats['total_revenue'] = (float)db_fetch_value($revenue_sql, $params) ?: 0;
    
    // Calculate average sale
    $stats['avg_sale'] = $total > 0 ? $stats['total_revenue'] / $total : 0;
    
    // Get total items sold
    $items_sql = "
        SELECT COALESCE(SUM(si.quantity), 0) as total_items
        FROM pos_sales s
        LEFT JOIN pos_sale_items si ON s.sale_id = si.sale_id
        WHERE $where
    ";
    $stats['total_items'] = (float)db_fetch_value($items_sql, $params) ?: 0;
    
    // Debug: Log the values for troubleshooting
    error_log("Revenue Stats - Total: {$stats['total_sales']}, Revenue: {$stats['total_revenue']}, Items: {$stats['total_items']}");
    
} catch (Exception $e) {
    error_log("Error calculating stats: " . $e->getMessage());
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>POS Sales History</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .btn-delete { transition: all 0.3s; }
            .btn-delete:hover { transform: scale(1.05); }
            .modal-header.bg-danger { background-color: #dc3545 !important; }
            .modal-header.bg-warning { background-color: #ffc107 !important; }
            .btn-close-white { filter: invert(1) grayscale(100%) brightness(200%); }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">POS Sales History</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">POS Sales History</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item active">Sales History</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <div id="flash-messages">
            <?php 
            if (function_exists('display_flash_messages')) {
                display_flash_messages();
            } else {
                // Fallback session flash display
                session_start();
                if (isset($_SESSION['flash_message'])) {
                    $flash_type = $_SESSION['flash_type'] ?? 'info';
                    $flash_message = $_SESSION['flash_message'];
                    ?>
                    <div class="alert alert-<?php echo $flash_type; ?> alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($flash_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php
                    unset($_SESSION['flash_message']);
                    unset($_SESSION['flash_type']);
                }
            }
            ?>
        </div>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total_sales']; ?></h3>
                        <p>Total Transactions</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-receipt"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_revenue']); ?></h3>
                        <p>Total Revenue</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['total_items']; ?></h3>
                        <p>Items Sold</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-boxes"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['avg_sale']); ?></h3>
                        <p>Average Transaction</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-body">
                        <a href="pos.php" class="btn btn-primary me-2">
                            <i class="fas fa-cash-register"></i> New Sale
                        </a>
                        <a href="void-refund.php" class="btn btn-warning me-2">
                            <i class="fas fa-undo-alt"></i> Void/Refund
                        </a>
                        <a href="../reports/daily-sales.php" class="btn btn-info me-2">
                            <i class="fas fa-chart-bar"></i> Sales Reports
                        </a>
                        <a href="../reports/product-sales.php" class="btn btn-info me-2">
                            <i class="fas fa-chart-bar"></i> Products Reports
                        </a>
                        <a href="../reports/cashier-sales.php" class="btn btn-info me-2">
                            <i class="fas fa-chart-bar"></i> Cashier Reports
                        </a>
                        <button type="button" class="btn btn-success" onclick="exportSales()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-2">
                        <input type="text" class="form-control" name="search" placeholder="Search receipt # or customer..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="outlet_id">
                            <option value="">All Outlets</option>
                            <?php foreach ($outlets as $outlet): ?>
                                <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>" <?php echo $outlet_id == ($outlet['outlet_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html($outlet['outlet_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="cashier_id">
                            <option value="">All Cashiers</option>
                            <?php foreach ($cashiers as $cashier): ?>
                                <option value="<?php echo $cashier['user_id'] ?? 0; ?>" <?php echo $cashier_id == ($cashier['user_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html(($cashier['first_name'] ?? '') . ' ' . ($cashier['last_name'] ?? '')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="voided" <?php echo $status == 'voided' ? 'selected' : ''; ?>>Voided</option>
                            <option value="refunded" <?php echo $status == 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-1"></i> Apply Filters
                        </button>
                        
                        <a href="?" class="btn btn-secondary">
                            <i class="fas fa-times me-1"></i> Clear
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Sales Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-list me-1"></i>
                    Sales Transactions (<?php echo $total; ?> total)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($sales)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-receipt fa-4x mb-3"></i>
                        <h5>No sales found</h5>
                        <p>Try adjusting your filters or create a new sale</p>
                        <a href="pos.php" class="btn btn-primary">
                            <i class="fas fa-plus me-1"></i> New Sale
                        </a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>
                                        <a href="?sort=receipt_number&order=<?php echo $sort === 'receipt_number' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="text-dark">
                                            Receipt #
                                            <?php if ($sort === 'receipt_number'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>
                                        <a href="?sort=sale_time&order=<?php echo $sort === 'sale_time' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="text-dark">
                                            Date/Time
                                            <?php if ($sort === 'sale_time'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Outlet</th>
                                    <th>Cashier</th>
                                    <th>Customer</th>
                                    <th class="text-center">Items</th>
                                    <th class="text-end">
                                        <a href="?sort=total_amount&order=<?php echo $sort === 'total_amount' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="text-dark">
                                            Amount
                                            <?php if ($sort === 'total_amount'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Payment Method</th>
                                    <th>Status</th>
                                    <th width="200">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sales as $sale): ?>
                                <tr class="<?php echo ($sale['payment_status'] ?? '') == 'voided' ? 'table-danger' : (($sale['payment_status'] ?? '') == 'refunded' ? 'table-warning' : ''); ?>">
                                    <td>
                                        <a href="receipt.php?id=<?php echo $sale['sale_id'] ?? 0; ?>">
                                            <strong><?php echo escape_html($sale['receipt_number'] ?? ''); ?></strong>
                                        </a>
                                    </td>
                                    <td>
                                        <?php echo !empty($sale['sale_time']) ? format_datetime($sale['sale_time']) : ''; ?>
                                        <br>
                                        <small class="text-muted"><?php echo !empty($sale['sale_time']) ? time_ago($sale['sale_time']) : ''; ?></small>
                                    </td>
                                    <td><?php echo escape_html($sale['outlet_name'] ?? ''); ?></td>
                                    <td><?php echo escape_html(($sale['first_name'] ?? '') . ' ' . ($sale['last_name'] ?? '')); ?></td>
                                    <td><?php echo !empty($sale['customer_name']) ? escape_html($sale['customer_name']) : 'Walk-in'; ?></td>
                                    <td class="text-center"><?php echo $sale['item_count'] ?? 0; ?></td>
                                    <td class="text-end"><?php echo format_currency($sale['total_amount'] ?? 0); ?></td>
                                    <td><?php echo ucfirst($sale['payment_method'] ?? 'Cash'); ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo ($sale['payment_status'] ?? '') == 'completed' ? 'success' : 
                                                (($sale['payment_status'] ?? '') == 'pending' ? 'warning' : 
                                                (($sale['payment_status'] ?? '') == 'voided' ? 'danger' : 
                                                (($sale['payment_status'] ?? '') == 'refunded' ? 'info' : 'secondary')));
                                        ?>">
                                            <?php echo ucfirst($sale['payment_status'] ?? 'unknown'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <a href="receipt.php?id=<?php echo $sale['sale_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View Receipt">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (file_exists('receipt-pdf.php')): ?>
                                            <a href="receipt-pdf.php?id=<?php echo $sale['sale_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-secondary" title="Download PDF" target="_blank">
                                                <i class="fas fa-file-pdf"></i>
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if (($sale['payment_status'] ?? '') == 'completed' && function_exists('has_permission') && has_permission('pos.sales.void')): ?>
                                                <button type="button" class="btn btn-sm btn-warning" 
                                                        onclick="voidSale(<?php echo $sale['sale_id'] ?? 0; ?>, '<?php echo escape_html($sale['receipt_number'] ?? ''); ?>')"
                                                        title="Void Transaction">
                                                    <i class="fas fa-ban"></i>
                                                </button>
                                            <?php endif; ?>
                                            
                                            <!-- Delete Button -->
                                            <button type="button" 
                                                    class="btn btn-sm btn-danger btn-delete" 
                                                    title="Delete Sale"
                                                    onclick="confirmDelete(<?php echo $sale['sale_id'] ?? 0; ?>, '<?php echo escape_html($sale['receipt_number'] ?? ''); ?>', '<?php echo $sale['payment_status'] ?? ''; ?>', <?php echo $sale['item_count'] ?? 0; ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer clearfix">
                <div class="row">
                    <div class="col-sm-5">
                        <span class="text-muted">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $per_page, $total); ?> of <?php echo $total; ?> sales
                        </span>
                    </div>
                    <div class="col-sm-7">
                        <ul class="pagination pagination-sm float-end">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&outlet_id=<?php echo $outlet_id; ?>&cashier_id=<?php echo $cashier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Void Sale Modal -->
<div class="modal fade" id="voidModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Void Transaction
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="void-refund.php" method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php endif; ?>
                <input type="hidden" name="action" value="void">
                <input type="hidden" name="sale_id" id="void_sale_id">
                
                <div class="modal-body">
                    <p>Are you sure you want to void transaction <strong id="void_receipt"></strong>?</p>
                    
                    <div class="mb-3">
                        <label for="void_reason" class="form-label">Reason for voiding</label>
                        <textarea class="form-control" id="void_reason" name="void_reason" rows="3" required></textarea>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Voiding will reverse the transaction and restore inventory. This cannot be undone.
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Void Transaction</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Sale Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Confirm Delete
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="deleteMessage" class="fs-5 mb-3"></p>
                
                <div id="deleteWarning" class="alert alert-warning d-none">
                    <i class="fas fa-info-circle me-2"></i>
                    <span id="deleteWarningText"></span>
                </div>
                
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <strong>Warning:</strong> This action cannot be undone. All related records will be permanently removed.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i> Cancel
                </button>
                <a href="#" id="confirmDeleteBtn" class="btn btn-danger">
                    <i class="fas fa-trash me-1"></i> Delete Permanently
                </a>
            </div>
        </div>
    </div>
</div>

<script>
function voidSale(saleId, receiptNumber) {
    document.getElementById('void_sale_id').value = saleId;
    document.getElementById('void_receipt').textContent = receiptNumber;
    
    const modal = new bootstrap.Modal(document.getElementById('voidModal'));
    modal.show();
}

function confirmDelete(saleId, receiptNumber, status, itemCount) {
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    const messageEl = document.getElementById('deleteMessage');
    const warningEl = document.getElementById('deleteWarning');
    const warningTextEl = document.getElementById('deleteWarningText');
    const confirmBtn = document.getElementById('confirmDeleteBtn');
    
    // Build the message
    let message = `Are you sure you want to delete transaction <strong>${receiptNumber}</strong>?`;
    messageEl.innerHTML = message;
    
    // Check if sale can be deleted
    if (status !== 'voided' && status !== 'refunded' && itemCount > 0) {
        warningEl.classList.remove('d-none');
        warningTextEl.textContent = `This sale has ${itemCount} item(s) and status "${status}". It should be voided first.`;
        confirmBtn.classList.add('disabled');
        confirmBtn.style.pointerEvents = 'none';
    } else {
        warningEl.classList.add('d-none');
        confirmBtn.classList.remove('disabled');
        confirmBtn.style.pointerEvents = 'auto';
    }
    
    // Set the delete link with current filters preserved
    const currentUrl = new URL(window.location.href);
    currentUrl.searchParams.set('delete', '1');
    currentUrl.searchParams.set('id', saleId);
    confirmBtn.href = currentUrl.toString();
    
    modal.show();
}

function exportSales() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.location.href = 'export-sales.php?' + params.toString();
}

// Debug function to check revenue calculation
function debugRevenue() {
    console.log('Stats:', <?php echo json_encode($stats); ?>);
}

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.ms-2 { margin-left: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.text-end { text-align: right; }
.float-end { float: right; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
.btn-group .btn { margin: 0 2px; }
.disabled { opacity: 0.5; cursor: not-allowed; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>