<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Shop.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$user = $auth->requireAuth();
$db = new Database();
$shop = new Shop();

$shop_id = $_GET['shop_id'] ?? null;

if (!$shop_id) {
    jsonResponse(['success' => false, 'message' => 'Shop ID is required.'], 400);
}

// Security Check: Ensure user is owner or admin
if (!$auth->hasRole('admin') && !$shop->isOwner($shop_id, $user['id'])) {
    jsonResponse(['success' => false, 'message' => 'Unauthorized to view these analytics.'], 403);
}

try {
    $analytics = [];

    // 1. Total Revenue and Orders from delivered orders
    $revenue_stmt = $db->query(
        "SELECT COALESCE(SUM(total_amount), 0) as total_revenue, COUNT(id) as total_orders 
         FROM orders 
         WHERE shop_id = ? AND status = 'delivered'",
        [$shop_id]
    );
    $revenue_data = $revenue_stmt->fetch(PDO::FETCH_ASSOC);
    $analytics['total_revenue'] = (float)$revenue_data['total_revenue'];
    $analytics['total_orders'] = (int)$revenue_data['total_orders'];

    // 2. Top Selling Products
    $top_products_stmt = $db->query(
        "SELECT 
            p.name, 
            SUM(oi.quantity) as total_quantity_sold, 
            SUM(oi.quantity * oi.price) as product_revenue
         FROM order_items oi
         JOIN orders o ON oi.order_id = o.id
         JOIN products p ON oi.product_id = p.id
         WHERE o.shop_id = ? AND o.status = 'delivered'
         GROUP BY p.id, p.name
         ORDER BY total_quantity_sold DESC
         LIMIT 5",
        [$shop_id]
    );
    $analytics['top_products'] = $top_products_stmt->fetchAll(PDO::FETCH_ASSOC);

    // 3. Sales over time
    $sales_over_time_stmt = $db->query(
        "SELECT 
            DATE(created_at) as sale_date, 
            SUM(total_amount) as daily_revenue
         FROM orders
         WHERE shop_id = ? AND status = 'delivered' AND created_at BETWEEN ? AND ?
         GROUP BY DATE(created_at)
         ORDER BY sale_date ASC",
        $params
    );
    $analytics['sales_over_time'] = $sales_over_time_stmt->fetchAll(PDO::FETCH_ASSOC);

    jsonResponse(['success' => true, 'analytics' => $analytics]);

} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>