<?php
/**
 * GET /api/business/dashboard.php
 * Business-only. Summary stats + recent sales activity.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

const LOW_STOCK_THRESHOLD = 3;

$userId = require_login();
require_role(['business']);

$pdo = Database::connect();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE owner_id = ? AND status = 'active'");
$stmt->execute([$userId]);
$activeListings = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE owner_id = ? AND status = 'active' AND quantity <= ?");
$stmt->execute([$userId, LOW_STOCK_THRESHOLD]);
$lowStock = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE owner_id = ? AND status = 'inactive'");
$stmt->execute([$userId]);
$inactiveListings = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE owner_id = ? AND status = 'sold'");
$stmt->execute([$userId]);
$soldListings = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare('SELECT COALESCE(SUM(quantity * unit_price), 0) FROM order_items WHERE seller_id = ? AND status = "fulfilled"');
$stmt->execute([$userId]);
$totalSales = round((float) $stmt->fetchColumn(), 2);

$stmt = $pdo->prepare('SELECT COUNT(*) FROM order_items WHERE seller_id = ? AND status = "pending"');
$stmt->execute([$userId]);
$pendingSales = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare('SELECT COUNT(DISTINCT order_id) FROM order_items WHERE seller_id = ? AND status = "fulfilled"');
$stmt->execute([$userId]);
$totalOrders = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare('
    SELECT oi.id AS order_item_id, oi.order_id, oi.quantity, oi.unit_price, oi.status, p.name AS product_name, o.created_at
    FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    JOIN products p ON p.id = oi.product_id
    WHERE oi.seller_id = ?
    ORDER BY o.created_at DESC
    LIMIT 10
');
$stmt->execute([$userId]);
$recentSales = $stmt->fetchAll();

send_json(true, 'OK', [
    'stats' => [
        'active_listings'   => $activeListings,
        'low_stock'         => $lowStock,
        'inactive_listings' => $inactiveListings,
        'sold_listings'     => $soldListings,
        'total_sales'       => $totalSales,
        'total_orders'      => $totalOrders,
        'pending_sales'     => $pendingSales,
    ],
    'recent_sales' => $recentSales,
]);
