<?php
include '../db.php';

header('Content-Type: application/json');

try {
    $start_date = $_GET['start_date'] ?? '';
    $end_date = $_GET['end_date'] ?? '';
    $type = $_GET['type'] ?? 'summary'; // summary, top_modifiers, trends

    // Build date filter
    $date_condition = '';
    if (!empty($start_date) && !empty($end_date)) {
        $start_sql = mysqli_real_escape_string($conn, $start_date);
        $end_sql = mysqli_real_escape_string($conn, $end_date);
        $date_condition = " AND s.sale_date BETWEEN '$start_sql 00:00:00' AND '$end_sql 23:59:59'";
    }

    switch ($type) {
        case 'summary':
            $query = "
                SELECT 
                    COUNT(DISTINCT s.id) as total_sales_with_modifiers,
                    COUNT(sim.id) as total_modifier_selections,
                    SUM(sim.price_adjustment) as total_modifier_revenue,
                    AVG(sim.price_adjustment) as avg_modifier_value,
                    (SELECT COUNT(*) FROM sales WHERE 1=1 $date_condition) as total_sales_period
                FROM sale_item_modifiers sim
                JOIN sale_items si ON sim.sale_item_id = si.id
                JOIN sales s ON si.sale_id = s.id
                WHERE 1=1 $date_condition
            ";
            
            $result = mysqli_query($conn, $query);
            $data = mysqli_fetch_assoc($result);
            
            // Calculate percentage
            $data['modifier_usage_percentage'] = $data['total_sales_period'] > 0 
                ? round(($data['total_sales_with_modifiers'] / $data['total_sales_period']) * 100, 1) 
                : 0;
            
            echo json_encode(['success' => true, 'data' => $data]);
            break;

        case 'top_modifiers':
            $limit = intval($_GET['limit'] ?? 10);
            $query = "
                SELECT 
                    sim.modifier_name,
                    img.display_name as group_name,
                    COUNT(sim.id) as usage_count,
                    SUM(sim.price_adjustment) as total_revenue
                FROM sale_item_modifiers sim
                JOIN item_modifier_groups img ON sim.modifier_group_id = img.id
                JOIN sale_items si ON sim.sale_item_id = si.id
                JOIN sales s ON si.sale_id = s.id
                WHERE 1=1 $date_condition
                GROUP BY sim.modifier_id, sim.modifier_name, img.display_name
                ORDER BY usage_count DESC
                LIMIT $limit
            ";
            
            $result = mysqli_query($conn, $query);
            $data = [];
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }
            
            echo json_encode(['success' => true, 'data' => $data]);
            break;

        case 'trends':
            $query = "
                SELECT 
                    DATE(s.sale_date) as sale_date,
                    COUNT(sim.id) as daily_selections,
                    SUM(sim.price_adjustment) as daily_revenue,
                    COUNT(DISTINCT s.id) as daily_orders_with_modifiers
                FROM sale_item_modifiers sim
                JOIN sale_items si ON sim.sale_item_id = si.id
                JOIN sales s ON si.sale_id = s.id
                WHERE 1=1 $date_condition
                GROUP BY DATE(s.sale_date)
                ORDER BY sale_date ASC
            ";
            
            $result = mysqli_query($conn, $query);
            $data = [];
            while ($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }
            
            echo json_encode(['success' => true, 'data' => $data]);
            break;

        default:
            throw new Exception('Invalid analytics type');
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
