<?php
// GET /api/seller/stats.php — Real seller statistics
require_once __DIR__ . '/../init.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') Response::error('Method not allowed.', 405);

$user = AuthMiddleware::verifyToken();
AuthMiddleware::requireRole(['seller', 'admin']);

$sellerId = (int)$user['id'];
$db = DB::conn();

// Total orders for this seller
$stmt = $db->prepare('SELECT COUNT(*) as cnt FROM orders WHERE seller_id = ?');
$stmt->execute([$sellerId]);
$totalOrders = (int)$stmt->fetch()['cnt'];

// Total revenue (delivered orders only)
$stmt = $db->prepare("SELECT COALESCE(SUM(total_amount),0) as rev FROM orders WHERE seller_id = ? AND status NOT IN ('cancelled')");
$stmt->execute([$sellerId]);
$totalRevenue = (float)$stmt->fetch()['rev'];

// Total products
$stmt = $db->prepare('SELECT COUNT(*) as cnt FROM products WHERE seller_id = ? AND is_active = 1');
$stmt->execute([$sellerId]);
$totalProducts = (int)$stmt->fetch()['cnt'];

// Unread messages
$stmt = $db->prepare('SELECT COUNT(*) as cnt FROM messages WHERE seller_id = ? AND sender_role = "buyer" AND is_read = 0');
$stmt->execute([$sellerId]);
$unreadMessages = (int)$stmt->fetch()['cnt'];

// Monthly revenue (last 6 months)
$stmt = $db->prepare("
    SELECT DATE_FORMAT(created_at,'%Y-%m') as month,
           COALESCE(SUM(total_amount),0) as revenue,
           COUNT(*) as orders
    FROM orders
    WHERE seller_id = ? AND status NOT IN ('cancelled')
      AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
    GROUP BY DATE_FORMAT(created_at,'%Y-%m')
    ORDER BY month ASC
");
$stmt->execute([$sellerId]);
$monthly = $stmt->fetchAll();

// Top products by sold_count
$stmt = $db->prepare(
    'SELECT id, name, price, stock, sold_count, image_url
     FROM products WHERE seller_id = ? AND is_active = 1
     ORDER BY sold_count DESC LIMIT 5'
);
$stmt->execute([$sellerId]);
$topProducts = $stmt->fetchAll();

Response::success('Stats fetched.', [
    'total_orders'    => $totalOrders,
    'total_revenue'   => $totalRevenue,
    'total_products'  => $totalProducts,
    'unread_messages' => $unreadMessages,
    'monthly'         => $monthly,
    'top_products'    => $topProducts,
]);
