<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Get selected date (default to today)
$selected_date = $_GET['date'] ?? date('Y-m-d');
$formatted_date = date('l, F j, Y', strtotime($selected_date));

// Get daily revenue statistics
$sql_daily_stats = "SELECT 
    COUNT(DISTINCT o.order_id) as total_orders,
    COUNT(DISTINCT o.customer_id) as unique_customers,
    COUNT(DISTINCT CASE WHEN c.registration_date = ? THEN c.customer_id END) as new_customers,
    COALESCE(SUM(o.total_amount), 0) as gross_revenue,
    COALESCE(SUM(o.discount_amount), 0) as total_discounts,
    COALESCE(SUM(o.tax_amount), 0) as total_taxes,
    COALESCE(SUM(o.total_amount - o.discount_amount), 0) as net_revenue,
    COALESCE(SUM(CASE WHEN o.status = 'DELIVERED' THEN o.total_amount ELSE 0 END), 0) as completed_revenue,
    COALESCE(SUM(CASE WHEN o.status != 'DELIVERED' THEN o.total_amount ELSE 0 END), 0) as pending_revenue,
    COUNT(CASE WHEN o.status = 'DELIVERED' THEN 1 END) as completed_orders,
    COUNT(CASE WHEN o.status != 'DELIVERED' THEN 1 END) as pending_orders
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
WHERE DATE(o.order_date) = ?";

$stmt_stats = $conn->prepare($sql_daily_stats);
$stmt_stats->bind_param("ss", $selected_date, $selected_date);
$stmt_stats->execute();
$daily_stats = $stmt_stats->get_result()->fetch_assoc();

// Get payment method breakdown
$sql_payment_methods = "SELECT 
    pm.method_name,
    pm.method_type,
    COUNT(p.payment_id) as payment_count,
    COALESCE(SUM(p.amount), 0) as total_amount
FROM payments p
JOIN payment_methods pm ON p.payment_method_id = pm.method_id
JOIN orders o ON p.order_id = o.order_id
WHERE DATE(p.payment_date) = ? AND p.status = 'COMPLETED'
GROUP BY pm.method_id, pm.method_name, pm.method_type
ORDER BY total_amount DESC";

$stmt_payments = $conn->prepare($sql_payment_methods);
$stmt_payments->bind_param("s", $selected_date);
$stmt_payments->execute();
$result_payment_methods = $stmt_payments->get_result();

// Get service performance
$sql_service_performance = "SELECT 
    s.service_name,
    sc.category_name,
    COUNT(oi.item_id) as order_count,
    SUM(oi.quantity) as total_pieces,
    COALESCE(SUM(oi.total_price), 0) as total_revenue,
    AVG(oi.unit_price) as avg_price
FROM order_items oi
JOIN services s ON oi.service_id = s.service_id
LEFT JOIN service_categories sc ON s.category_id = sc.category_id
JOIN orders o ON oi.order_id = o.order_id
WHERE DATE(o.order_date) = ?
GROUP BY s.service_id, s.service_name, sc.category_name
ORDER BY total_revenue DESC";

$stmt_services = $conn->prepare($sql_service_performance);
$stmt_services->bind_param("s", $selected_date);
$stmt_services->execute();
$result_services = $stmt_services->get_result();

// Get hourly revenue distribution
$sql_hourly_revenue = "SELECT 
    HOUR(o.created_at) as hour,
    COUNT(o.order_id) as order_count,
    COALESCE(SUM(o.total_amount), 0) as revenue
FROM orders o
WHERE DATE(o.order_date) = ?
GROUP BY HOUR(o.created_at)
ORDER BY hour";

$stmt_hourly = $conn->prepare($sql_hourly_revenue);
$stmt_hourly->bind_param("s", $selected_date);
$stmt_hourly->execute();
$result_hourly = $stmt_hourly->get_result();

$hourly_data = array_fill(0, 24, ['hour' => 0, 'order_count' => 0, 'revenue' => 0]);
while ($row = $result_hourly->fetch_assoc()) {
    $hourly_data[$row['hour']] = $row;
    $hourly_data[$row['hour']]['hour'] = $row['hour'];
}

// Get daily orders detail
$sql_daily_orders = "SELECT 
    o.order_id,
    o.order_number,
    o.order_date,
    o.status,
    o.total_amount,
    o.payment_status,
    c.first_name,
    c.last_name,
    c.phone,
    u.full_name as created_by_name,
    COUNT(oi.item_id) as item_count
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
LEFT JOIN users u ON o.created_by = u.user_id
LEFT JOIN order_items oi ON o.order_id = oi.order_id
WHERE DATE(o.order_date) = ?
GROUP BY o.order_id
ORDER BY o.created_at DESC";

$stmt_orders = $conn->prepare($sql_daily_orders);
$stmt_orders->bind_param("s", $selected_date);
$stmt_orders->execute();
$result_orders = $stmt_orders->get_result();

// Get previous day for comparison
$previous_date = date('Y-m-d', strtotime($selected_date . ' -1 day'));
$sql_previous_stats = "SELECT 
    COALESCE(SUM(total_amount), 0) as prev_revenue,
    COUNT(order_id) as prev_orders
FROM orders 
WHERE DATE(order_date) = ?";

$stmt_prev = $conn->prepare($sql_previous_stats);
$stmt_prev->bind_param("s", $previous_date);
$stmt_prev->execute();
$previous_stats = $stmt_prev->get_result()->fetch_assoc();

// Calculate changes
$revenue_change = $previous_stats['prev_revenue'] > 0 ? 
    (($daily_stats['gross_revenue'] - $previous_stats['prev_revenue']) / $previous_stats['prev_revenue']) * 100 : 0;
$orders_change = $previous_stats['prev_orders'] > 0 ? 
    (($daily_stats['total_orders'] - $previous_stats['prev_orders']) / $previous_stats['prev_orders']) * 100 : 0;

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Daily Revenue - Laundry System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .chart-header {
            padding: 1.5rem 1.5rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .chart-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 1rem 0;
        }
        
        .chart-body {
            padding: 1rem 1.5rem 1.5rem;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-in-progress { background: #dbeafe; color: #1d4ed8; }
        .status-ready { background: #dcfce7; color: #166534; }
        .status-delivered { background: #dcfce7; color: #166534; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        .status-paid { background: #dcfce7; color: #166534; }
        .status-partial { background: #fef3c7; color: #92400e; }
        .status-unpaid { background: #fee2e2; color: #991b1b; }
        
        .date-selector {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .change-positive { color: #059669; }
        .change-negative { color: #dc2626; }
        .change-neutral { color: #64748b; }
        
        .payment-method-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .service-performance-item {
            border-bottom: 1px solid #e2e8f0;
            padding: 0.75rem 0;
        }
        
        .service-performance-item:last-child {
            border-bottom: none;
        }
        
        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Daily Revenue Report</h2>
                                <p class="mb-0">Revenue analysis and performance metrics for <?php echo $formatted_date; ?></p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" onclick="printReport()">
                                    <i class="bi bi-printer me-2"></i>Print Report
                                </button>
                                <button type="button" class="btn btn-outline-light" onclick="exportReport()">
                                    <i class="bi bi-download me-2"></i>Export
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Date Selector -->
                    <div class="date-selector">
                        <div class="row align-items-center">
                            <div class="col-md-4">
                                <label class="form-label">Select Date</label>
                                <input type="date" class="form-control" id="dateSelector" value="<?php echo $selected_date; ?>" max="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="col-md-8">
                                <div class="d-flex gap-2 mt-3 mt-md-0">
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="changeDate(-1)">
                                        <i class="bi bi-chevron-left"></i> Previous Day
                                    </button>
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="setToday()">
                                        Today
                                    </button>
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="changeDate(1)" <?php echo $selected_date >= date('Y-m-d') ? 'disabled' : ''; ?>>
                                        Next Day <i class="bi bi-chevron-right"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-title">Gross Revenue</div>
                            <div class="stat-value" style="color: #059669;">KES <?php echo number_format($daily_stats['gross_revenue']); ?></div>
                            <div class="stat-change <?php echo $revenue_change > 0 ? 'change-positive' : ($revenue_change < 0 ? 'change-negative' : 'change-neutral'); ?>">
                                <?php if($revenue_change != 0): ?>
                                    <i class="bi bi-<?php echo $revenue_change > 0 ? 'arrow-up' : 'arrow-down'; ?>"></i>
                                    <?php echo abs(number_format($revenue_change, 1)); ?>% from yesterday
                                <?php else: ?>
                                    No change from yesterday
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Total Orders</div>
                            <div class="stat-value"><?php echo number_format($daily_stats['total_orders']); ?></div>
                            <div class="stat-change <?php echo $orders_change > 0 ? 'change-positive' : ($orders_change < 0 ? 'change-negative' : 'change-neutral'); ?>">
                                <?php if($orders_change != 0): ?>
                                    <i class="bi bi-<?php echo $orders_change > 0 ? 'arrow-up' : 'arrow-down'; ?>"></i>
                                    <?php echo abs(number_format($orders_change, 1)); ?>% from yesterday
                                <?php else: ?>
                                    No change from yesterday
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Unique Customers</div>
                            <div class="stat-value" style="color: #7c3aed;"><?php echo number_format($daily_stats['unique_customers']); ?></div>
                            <div class="stat-change change-neutral">
                                <?php echo number_format($daily_stats['new_customers']); ?> new customers
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Completed Revenue</div>
                            <div class="stat-value" style="color: #059669;">KES <?php echo number_format($daily_stats['completed_revenue']); ?></div>
                            <div class="stat-change change-neutral">
                                <?php echo number_format($daily_stats['completed_orders']); ?> delivered orders
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Pending Revenue</div>
                            <div class="stat-value" style="color: #d97706;">KES <?php echo number_format($daily_stats['pending_revenue']); ?></div>
                            <div class="stat-change change-neutral">
                                <?php echo number_format($daily_stats['pending_orders']); ?> pending orders
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Net Revenue</div>
                            <div class="stat-value" style="color: #059669;">KES <?php echo number_format($daily_stats['net_revenue']); ?></div>
                            <div class="stat-change change-neutral">
                                After discounts: KES <?php echo number_format($daily_stats['total_discounts']); ?>
                            </div>
                        </div>
                    </div>

                    <!-- Charts Row -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Hourly Revenue Distribution</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="hourlyChart" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Payment Methods</h3>
                                </div>
                                <div class="chart-body">
                                    <?php 
                                    $result_payment_methods->data_seek(0);
                                    if($result_payment_methods->num_rows > 0): ?>
                                        <?php while($row = $result_payment_methods->fetch_assoc()): ?>
                                        <div class="payment-method-card">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <div style="font-weight: 600;"><?php echo $row['method_name']; ?></div>
                                                    <small style="color: #64748b;"><?php echo $row['payment_count']; ?> transactions</small>
                                                </div>
                                                <div class="text-end">
                                                    <div style="font-weight: 600; color: #059669;">
                                                        KES <?php echo number_format($row['total_amount']); ?>
                                                    </div>
                                                    <small style="color: #64748b;">
                                                        <?php echo $daily_stats['gross_revenue'] > 0 ? number_format(($row['total_amount'] / $daily_stats['gross_revenue']) * 100, 1) : 0; ?>%
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-4">
                                            <p style="color: #64748b;">No payments recorded for this date</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Service Performance and Orders -->
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Service Performance</h3>
                                </div>
                                <div style="padding: 1.5rem;">
                                    <?php 
                                    $result_services->data_seek(0);
                                    if($result_services->num_rows > 0): ?>
                                        <?php while($row = $result_services->fetch_assoc()): ?>
                                        <div class="service-performance-item">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <div style="font-weight: 600;"><?php echo $row['service_name']; ?></div>
                                                    <small style="color: #64748b;">
                                                        <?php echo $row['category_name'] ?: 'General'; ?> • 
                                                        <?php echo $row['total_pieces']; ?> pieces • 
                                                        <?php echo $row['order_count']; ?> orders
                                                    </small>
                                                </div>
                                                <div class="text-end">
                                                    <div style="font-weight: 600; color: #059669;">
                                                        KES <?php echo number_format($row['total_revenue']); ?>
                                                    </div>
                                                    <small style="color: #64748b;">
                                                        Avg: KES <?php echo number_format($row['avg_price'], 2); ?>
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-4">
                                            <p style="color: #64748b;">No services performed on this date</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-6">
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Daily Orders</h3>
                                </div>
                                <div class="table-responsive">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Order #</th>
                                                <th>Customer</th>
                                                <th>Items</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th>Payment</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $result_orders->data_seek(0);
                                            if($result_orders->num_rows > 0): ?>
                                                <?php while($row = $result_orders->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <a href="view_order.php?id=<?php echo $row['order_id']; ?>" style="color: #059669; text-decoration: none; font-weight: 600;">
                                                            <?php echo $row['order_number']; ?>
                                                        </a>
                                                        <br>
                                                        <small style="color: #64748b;"><?php echo date('g:i A', strtotime($row['order_date'])); ?></small>
                                                    </td>
                                                    <td>
                                                        <div style="font-weight: 600;"><?php echo $row['first_name'] . ' ' . $row['last_name']; ?></div>
                                                        <small style="color: #64748b;"><?php echo $row['phone']; ?></small>
                                                    </td>
                                                    <td>
                                                        <span style="font-weight: 600;"><?php echo $row['item_count']; ?></span> items
                                                    </td>
                                                    <td style="font-weight: 600; color: #059669;">
                                                        KES <?php echo number_format($row['total_amount']); ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $status_class = match(strtolower($row['status'])) {
                                                            'pending' => 'status-pending',
                                                            'in_progress' => 'status-in-progress',
                                                            'ready' => 'status-ready',
                                                            'delivered' => 'status-delivered',
                                                            'cancelled' => 'status-cancelled',
                                                            default => 'status-pending'
                                                        };
                                                        ?>
                                                        <span class="status-badge <?php echo $status_class; ?>">
                                                            <?php echo ucfirst(str_replace('_', ' ', $row['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $payment_class = match(strtolower($row['payment_status'])) {
                                                            'paid' => 'status-paid',
                                                            'partial' => 'status-partial',
                                                            'pending' => 'status-unpaid',
                                                            default => 'status-unpaid'
                                                        };
                                                        ?>
                                                        <span class="status-badge <?php echo $payment_class; ?>">
                                                            <?php echo ucfirst($row['payment_status']); ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="6" class="text-center" style="color: #64748b; padding: 2rem;">
                                                        No orders found for this date
                                                    </td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    
    <script>
    // Hourly chart
    const hourlyData = <?php echo json_encode($hourly_data); ?>;
    
    const hourlyOptions = {
        series: [{
            name: 'Revenue (KES)',
            type: 'column',
            data: hourlyData.map(item => item.revenue)
        }, {
            name: 'Orders',
            type: 'line',
            data: hourlyData.map(item => item.order_count)
        }],
        chart: {
            height: 350,
            type: 'line',
            toolbar: { show: false }
        },
        stroke: {
            width: [0, 4]
        },
        dataLabels: {
            enabled: true,
            enabledOnSeries: [1]
        },
        labels: hourlyData.map(item => item.hour + ':00'),
        xaxis: {
            type: 'category',
            title: {
                text: 'Hour of Day'
            }
        },
        yaxis: [{
            title: {
                text: 'Revenue (KES)'
            }
        }, {
            opposite: true,
            title: {
                text: 'Number of Orders'
            }
        }],
        colors: ['#059669', '#7c3aed'],
        grid: {
            borderColor: '#e2e8f0'
        }
    };

    const hourlyChart = new ApexCharts(document.querySelector("#hourlyChart"), hourlyOptions);
    hourlyChart.render();

    // Date navigation
    function changeDate(days) {
        const currentDate = new Date(document.getElementById('dateSelector').value);
        currentDate.setDate(currentDate.getDate() + days);
        const newDate = currentDate.toISOString().split('T')[0];
        window.location.href = `?date=${newDate}`;
    }

    function setToday() {
        const today = new Date().toISOString().split('T')[0];
        window.location.href = `?date=${today}`;
    }

    // Date selector change
    document.getElementById('dateSelector').addEventListener('change', function() {
        window.location.href = `?date=${this.value}`;
    });

    // Export and print functions
    function exportReport() {
        const date = document.getElementById('dateSelector').value;
        window.open(`export_daily_revenue.php?date=${date}`, '_blank');
    }

    function printReport() {
        window.print();
    }
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>