<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Daily Sales Report - COMPLETE FIXED VERSION
 * 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
$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')) {
    $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;
    }
}

// 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_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Set page title
$page_title = 'Daily Sales Report';

// 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 date from request and convert if needed
$date_input = $_GET['date'] ?? date('Y-m-d');
// Convert date from d/m/Y to Y-m-d if needed
if (strpos($date_input, '/') !== false) {
    $parts = explode('/', $date_input);
    if (count($parts) == 3) {
        // Assuming format is d/m/Y
        $date = $parts[2] . '-' . $parts[1] . '-' . $parts[0];
    } else {
        $date = $date_input;
    }
} else {
    $date = $date_input;
}

$outlet_id = isset($_GET['outlet_id']) ? (int)$_GET['outlet_id'] : null;
$export = $_GET['export'] ?? '';

// Get outlets for filter
$outlets = [];
try {
    if (function_exists('db_fetch_all')) {
        $outlets = db_fetch_all("SELECT outlet_id, outlet_name FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name") ?: [];
    } else {
        // Manual query for outlets
        global $db;
        if (isset($db) && $db instanceof mysqli) {
            $result = $db->query("SELECT outlet_id, outlet_name FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name");
            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $outlets[] = $row;
                }
            }
        }
    }
} catch (Exception $e) {
    error_log("Error fetching outlets: " . $e->getMessage());
}

// Get report data
$report = get_daily_sales_report($date, $outlet_id);

// Handle export
if ($export === 'pdf') {
    export_pdf($report, $date);
} elseif ($export === 'excel') {
    export_excel($report, $date);
} elseif ($export === 'csv') {
    export_csv($report, $date);
}

// 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>Daily Sales Report</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; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; padding: 15px; }
            .small-box .inner { padding: 10px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-success { background-color: #28a745 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
        </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="#">Daily Sales Report</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">Daily Sales Report</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"><a href="../reports/index.php">Reports</a></li>
                    <li class="breadcrumb-item active">Daily Sales</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Date Selection -->
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label for="date" class="form-label">Date:</label>
                        <input type="date" class="form-control" id="date" name="date" value="<?php echo $date; ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <label for="outlet_id" class="form-label">Outlet:</label>
                        <select class="form-select" id="outlet_id" 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-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> View Report
                        </button>
                    </div>
                    
                    <div class="col-md-3 d-flex align-items-end gap-2">
                        <a href="?date=<?php echo $date; ?>&outlet_id=<?php echo $outlet_id; ?>&export=pdf" class="btn btn-danger">
                            <i class="fas fa-file-pdf"></i> PDF
                        </a>
                        <a href="?date=<?php echo $date; ?>&outlet_id=<?php echo $outlet_id; ?>&export=excel" class="btn btn-success">
                            <i class="fas fa-file-excel"></i> Excel
                        </a>
                        <a href="?date=<?php echo $date; ?>&outlet_id=<?php echo $outlet_id; ?>&export=csv" class="btn btn-info">
                            <i class="fas fa-file-csv"></i> CSV
                        </a>
                    </div>
                </form>
            </div>
        </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 number_format($report['summary']['transactions'] ?? 0); ?></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($report['summary']['total_sales'] ?? 0); ?></h3>
                        <p>Total Sales</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 number_format($report['summary']['items_sold'] ?? 0); ?></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($report['summary']['avg_ticket'] ?? 0); ?></h3>
                        <p>Average Ticket</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Transactions List -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list me-1"></i>
                            Transactions
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Time</th>
                                        <th>Receipt #</th>
                                        <th>Customer</th>
                                        <th>Payment Method</th>
                                        <th class="text-end">Items</th>
                                        <th class="text-end">Amount</th>
                                        <th class="text-center">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($report['transactions'])): ?>
                                        <tr>
                                            <td colspan="7" class="text-center text-muted py-5">
                                                <i class="fas fa-receipt fa-3x mb-3"></i>
                                                <h5>No transactions found for this date</h5>
                                                <p class="mb-0">Try selecting a different date or outlet</p>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php 
                                        $total_amount = 0;
                                        foreach ($report['transactions'] as $trans): 
                                            $total_amount += (float)($trans['total_amount'] ?? 0);
                                        ?>
                                        <tr>
                                            <td><?php echo !empty($trans['sale_time']) ? date('H:i', strtotime($trans['sale_time'])) : '--:--'; ?></td>
                                            <td>
                                                <strong><?php echo escape_html($trans['receipt_number'] ?? 'N/A'); ?></strong>
                                            </td>
                                            <td>
                                                <?php 
                                                if (!empty($trans['customer_name'])) {
                                                    echo '<i class="fas fa-user me-1"></i>' . escape_html($trans['customer_name']);
                                                } elseif (!empty($trans['customer_id'])) {
                                                    echo '<i class="fas fa-user me-1"></i>Customer #' . $trans['customer_id'];
                                                } else {
                                                    echo '<span class="text-muted"><i class="fas fa-user me-1"></i>Walk-in</span>';
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $method = strtolower($trans['payment_method'] ?? $trans['payment_type'] ?? 'cash');
                                                $badge_color = 'secondary';
                                                $icon = 'fa-money-bill';
                                                
                                                if (strpos($method, 'cash') !== false) {
                                                    $badge_color = 'success';
                                                    $icon = 'fa-money-bill-wave';
                                                } elseif (strpos($method, 'card') !== false || strpos($method, 'credit') !== false) {
                                                    $badge_color = 'info';
                                                    $icon = 'fa-credit-card';
                                                } elseif (strpos($method, 'mobile') !== false || strpos($method, 'momo') !== false) {
                                                    $badge_color = 'warning';
                                                    $icon = 'fa-mobile-alt';
                                                } elseif (strpos($method, 'bank') !== false) {
                                                    $badge_color = 'primary';
                                                    $icon = 'fa-university';
                                                }
                                                ?>
                                                <span class="badge bg-<?php echo $badge_color; ?>">
                                                    <i class="fas <?php echo $icon; ?> me-1"></i>
                                                    <?php echo ucwords(str_replace('_', ' ', $method)); ?>
                                                </span>
                                            </td>
                                            <td class="text-end">
                                                <span class="badge bg-secondary">
                                                    <?php echo number_format($trans['item_count'] ?? 0); ?>
                                                </span>
                                            </td>
                                            <td class="text-end">
                                                <strong><?php echo format_currency($trans['total_amount'] ?? 0); ?></strong>
                                            </td>
                                            <td class="text-center">
                                                <a href="/HMSPOS/pos/sales/receipt.php?id=<?php echo $trans['sale_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-outline-primary" 
                                                   title="View Receipt"
                                                   target="_blank">
                                                    <i class="fas fa-receipt"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                        <!-- Summary Row -->
                                        <tr class="table-info fw-bold">
                                            <td colspan="5" class="text-end">Total:</td>
                                            <td class="text-end"><?php echo format_currency($total_amount); ?></td>
                                            <td></td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php
/**
 * Get daily sales report data - FIXED with correct column names
 */
function get_daily_sales_report($date, $outlet_id = null) {
    $report = [
        'summary' => [
            'transactions' => 0,
            'total_sales' => 0,
            'items_sold' => 0,
            'avg_ticket' => 0
        ],
        'transactions' => []
    ];
    
    // Log the input parameters for debugging
    error_log("Daily Sales Report - Date: $date, Outlet ID: " . ($outlet_id ?: 'All'));
    
    try {
        global $db;
        
        // Try to establish database connection if not exists
        if (!isset($db) || !($db instanceof mysqli)) {
            // Try to connect directly
            $host = defined('DB_HOST') ? DB_HOST : 'localhost';
            $user = defined('DB_USER') ? DB_USER : 'root';
            $pass = defined('DB_PASS') ? DB_PASS : '';
            $dbname = defined('DB_NAME') ? DB_NAME : 'hmspos';
            
            $db = new mysqli($host, $user, $pass, $dbname);
            
            if ($db->connect_error) {
                error_log("Database connection failed: " . $db->connect_error);
                return $report;
            }
        }
        
        // First, let's check what columns actually exist in the table
        $columns_result = $db->query("SHOW COLUMNS FROM pos_sales");
        $columns = [];
        if ($columns_result) {
            while ($col = $columns_result->fetch_assoc()) {
                $columns[] = $col['Field'];
            }
            error_log("Available columns in pos_sales: " . implode(", ", $columns));
        }
        
        // Build the SELECT part dynamically based on existing columns
        $select_fields = ['s.sale_id', 's.receipt_number', 's.sale_time', 's.total_amount'];
        
        // Check for customer-related columns
        if (in_array('customer_name', $columns)) {
            $select_fields[] = 's.customer_name';
        } elseif (in_array('customer_id', $columns)) {
            $select_fields[] = 's.customer_id';
            // Try to join with customers table if it exists
            $customer_join = " LEFT JOIN customers c ON s.customer_id = c.customer_id";
            $select_fields[] = 'c.full_name as customer_name';
        } else {
            $select_fields[] = "NULL as customer_name";
            $select_fields[] = "NULL as customer_id";
        }
        
        // Check for payment method columns
        if (in_array('payment_method', $columns)) {
            $select_fields[] = 's.payment_method';
        } elseif (in_array('payment_type', $columns)) {
            $select_fields[] = 's.payment_type as payment_method';
        } elseif (in_array('payment_mode', $columns)) {
            $select_fields[] = 's.payment_mode as payment_method';
        } else {
            $select_fields[] = "'cash' as payment_method";
        }
        
        // Check for outlet_id column
        if (in_array('outlet_id', $columns)) {
            // We'll use it in WHERE clause if needed
        }
        
        // Build the WHERE clause
        $where_conditions = ["DATE(s.sale_time) = ?"];
        $params = [$date];
        $types = "s";
        
        if ($outlet_id && in_array('outlet_id', $columns)) {
            $where_conditions[] = "s.outlet_id = ?";
            $params[] = $outlet_id;
            $types .= "i";
        }
        
        $where_clause = implode(" AND ", $where_conditions);
        
        // Check if pos_sale_items table exists for item count
        $items_table_check = $db->query("SHOW TABLES LIKE 'pos_sale_items'");
        $has_items_table = $items_table_check && $items_table_check->num_rows > 0;
        
        if ($has_items_table) {
            $item_count_subquery = "(SELECT COALESCE(SUM(quantity), 0) FROM pos_sale_items WHERE sale_id = s.sale_id) as item_count";
        } else {
            // Check if items are stored directly in sales table
            if (in_array('item_count', $columns)) {
                $item_count_subquery = "s.item_count";
            } elseif (in_array('total_items', $columns)) {
                $item_count_subquery = "s.total_items as item_count";
            } else {
                $item_count_subquery = "0 as item_count";
            }
        }
        
        // Build the complete query
        $sql = "SELECT 
                    " . implode(", ", $select_fields) . ",
                    $item_count_subquery
                FROM pos_sales s
                " . (isset($customer_join) ? $customer_join : "") . "
                WHERE $where_clause
                ORDER BY s.sale_time";
        
        error_log("SQL Query: " . $sql);
        
        // Prepare and execute
        $stmt = $db->prepare($sql);
        if ($stmt) {
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $transactions = [];
            while ($row = $result->fetch_assoc()) {
                $transactions[] = $row;
            }
            
            $report['transactions'] = $transactions;
            $stmt->close();
            
            error_log("Found " . count($transactions) . " transactions");
        } else {
            error_log("MySQLi prepare error: " . $db->error);
            
            // Fallback to simple query without prepared statement
            $safe_date = $db->real_escape_string($date);
            $fallback_sql = "SELECT 
                                s.*,
                                (SELECT COALESCE(SUM(quantity), 0) FROM pos_sale_items WHERE sale_id = s.sale_id) as item_count
                            FROM pos_sales s 
                            WHERE DATE(s.sale_time) = '$safe_date'";
            
            if ($outlet_id && in_array('outlet_id', $columns)) {
                $safe_outlet = (int)$outlet_id;
                $fallback_sql .= " AND s.outlet_id = $safe_outlet";
            }
            
            $fallback_sql .= " ORDER BY s.sale_time";
            
            $result = $db->query($fallback_sql);
            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $report['transactions'][] = $row;
                }
                error_log("Fallback query found " . count($report['transactions']) . " transactions");
            } else {
                error_log("Fallback query failed: " . $db->error);
            }
        }
        
        // Calculate summary
        $report['summary']['transactions'] = count($report['transactions']);
        
        $total_sales = 0;
        $items_sold = 0;
        
        foreach ($report['transactions'] as $trans) {
            $total_sales += (float)($trans['total_amount'] ?? 0);
            $items_sold += (int)($trans['item_count'] ?? 0);
        }
        
        $report['summary']['total_sales'] = $total_sales;
        $report['summary']['items_sold'] = $items_sold;
        $report['summary']['avg_ticket'] = $report['summary']['transactions'] > 0 
            ? $total_sales / $report['summary']['transactions'] 
            : 0;
        
        error_log("Report Summary - Transactions: {$report['summary']['transactions']}, Total Sales: $total_sales");
        
    } catch (Exception $e) {
        error_log("Error generating daily sales report: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
    }
    
    return $report;
}

/**
 * Export as PDF
 */
function export_pdf($report, $date) {
    // Simple HTML export as fallback
    export_html($report, $date);
}

/**
 * Export as HTML
 */
function export_html($report, $date) {
    header('Content-Type: text/html');
    header('Content-Disposition: attachment; filename="daily_sales_' . date('Y-m-d', strtotime($date)) . '.html"');
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Daily Sales Report - <?php echo format_date($date); ?></title>
        <style>
            body { font-family: Arial, sans-serif; margin: 20px; }
            h1 { color: #333; border-bottom: 2px solid #333; padding-bottom: 10px; }
            h2 { color: #666; margin-top: 30px; }
            table { border-collapse: collapse; width: 100%; margin: 20px 0; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
            .text-right { text-align: right; }
            .summary-box { 
                display: inline-block; 
                width: 200px; 
                padding: 15px; 
                margin: 10px; 
                background: #f8f9fa; 
                border: 1px solid #dee2e6;
                border-radius: 5px;
            }
            .summary-box h3 { margin: 0 0 10px 0; color: #666; }
            .summary-box .value { font-size: 24px; font-weight: bold; color: #007bff; }
        </style>
    </head>
    <body>
        <h1>Daily Sales Report - <?php echo format_date($date); ?></h1>
        
        <?php if ($report['summary']['transactions'] == 0): ?>
            <p>No sales data found for this date.</p>
        <?php else: ?>
            <h2>Summary</h2>
            <div style="margin: 20px 0;">
                <div class="summary-box">
                    <h3>Total Transactions</h3>
                    <div class="value"><?php echo number_format($report['summary']['transactions']); ?></div>
                </div>
                <div class="summary-box">
                    <h3>Total Sales</h3>
                    <div class="value"><?php echo format_currency($report['summary']['total_sales']); ?></div>
                </div>
                <div class="summary-box">
                    <h3>Items Sold</h3>
                    <div class="value"><?php echo number_format($report['summary']['items_sold']); ?></div>
                </div>
                <div class="summary-box">
                    <h3>Average Ticket</h3>
                    <div class="value"><?php echo format_currency($report['summary']['avg_ticket']); ?></div>
                </div>
            </div>
            
            <h2>Transactions</h2>
            <table>
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Receipt #</th>
                        <th>Customer</th>
                        <th>Payment Method</th>
                        <th class="text-right">Items</th>
                        <th class="text-right">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($report['transactions'] as $trans): ?>
                    <tr>
                        <td><?php echo date('H:i', strtotime($trans['sale_time'])); ?></td>
                        <td><?php echo $trans['receipt_number'] ?? ''; ?></td>
                        <td><?php echo $trans['customer_name'] ?: 'Walk-in'; ?></td>
                        <td><?php echo ucfirst($trans['payment_method'] ?? 'Cash'); ?></td>
                        <td class="text-right"><?php echo number_format($trans['item_count'] ?? 0); ?></td>
                        <td class="text-right"><?php echo format_currency($trans['total_amount'] ?? 0); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr style="font-weight: bold; background: #f2f2f2;">
                        <td colspan="5" class="text-right">Total:</td>
                        <td class="text-right"><?php echo format_currency($report['summary']['total_sales']); ?></td>
                    </tr>
                </tfoot>
            </table>
        <?php endif; ?>
        
        <p style="margin-top: 30px; color: #666; font-size: 12px; text-align: center;">
            Generated on <?php echo date('Y-m-d H:i:s'); ?>
        </p>
    </body>
    </html>
    <?php
    exit;
}

/**
 * Export as Excel
 */
function export_excel($report, $date) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="daily_sales_' . date('Y-m-d', strtotime($date)) . '.xls"');
    
    echo "Daily Sales Report - " . format_date($date) . "\n\n";
    
    if ($report['summary']['transactions'] == 0) {
        echo "No sales data found for this date.\n";
        exit;
    }
    
    echo "SUMMARY\n";
    echo "Transactions\t" . $report['summary']['transactions'] . "\n";
    echo "Total Sales\t" . $report['summary']['total_sales'] . "\n";
    echo "Items Sold\t" . $report['summary']['items_sold'] . "\n";
    echo "Average Ticket\t" . $report['summary']['avg_ticket'] . "\n\n";
    
    echo "TRANSACTIONS\n";
    echo "Time\tReceipt\tCustomer\tPayment Method\tItems\tAmount\n";
    foreach ($report['transactions'] as $trans) {
        echo date('H:i', strtotime($trans['sale_time'])) . "\t";
        echo ($trans['receipt_number'] ?? 'N/A') . "\t";
        echo ($trans['customer_name'] ?: 'Walk-in') . "\t";
        echo ucfirst($trans['payment_method'] ?? 'Cash') . "\t";
        echo ($trans['item_count'] ?? 0) . "\t";
        echo ($trans['total_amount'] ?? 0) . "\n";
    }
    exit;
}

/**
 * Export as CSV
 */
function export_csv($report, $date) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="daily_sales_' . date('Y-m-d', strtotime($date)) . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['Daily Sales Report - ' . format_date($date)]);
    fputcsv($output, []);
    
    if ($report['summary']['transactions'] == 0) {
        fputcsv($output, ['No sales data found for this date.']);
        fclose($output);
        exit;
    }
    
    fputcsv($output, ['SUMMARY']);
    fputcsv($output, ['Transactions', $report['summary']['transactions']]);
    fputcsv($output, ['Total Sales', $report['summary']['total_sales']]);
    fputcsv($output, ['Items Sold', $report['summary']['items_sold']]);
    fputcsv($output, ['Average Ticket', $report['summary']['avg_ticket']]);
    fputcsv($output, []);
    
    fputcsv($output, ['TRANSACTIONS']);
    fputcsv($output, ['Time', 'Receipt', 'Customer', 'Payment Method', 'Items', 'Amount']);
    foreach ($report['transactions'] as $trans) {
        fputcsv($output, [
            date('H:i', strtotime($trans['sale_time'])),
            $trans['receipt_number'] ?? 'N/A',
            $trans['customer_name'] ?: 'Walk-in',
            ucfirst($trans['payment_method'] ?? 'Cash'),
            $trans['item_count'] ?? 0,
            $trans['total_amount'] ?? 0
        ]);
    }
    
    fclose($output);
    exit;
}

// 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>';
}
?>