<?php
declare(strict_types=1);

require_once __DIR__ . '/../models/Product.php';
require_once __DIR__ . '/../models/Order.php';
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../config/database.php';

class AdminController
{
    public function dashboard(): array
    {
        $orders = (new Order())->latest(12);
        $products = (new Product())->all(10, true);
        $usersSample = (new User())->all(12);
        $sales = 0;
        foreach ($orders as $order) {
            $sales += (float)$order['total_amount'];
        }

        $paidOrders = 0;
        foreach ($orders as $order) {
            if (($order['payment_status'] ?? '') === 'paid') {
                $paidOrders++;
            }
        }

        $salesSeries = $this->salesLastSevenDays();
        $counts = $this->globalCounts();
        try {
            $lowStock = (new Product())->lowStock(5, 15);
        } catch (Throwable $e) {
            $lowStock = [];
        }

        return [
            'orders' => $orders,
            'products' => $products,
            'users' => $usersSample,
            'sales_series' => $salesSeries,
            'low_stock' => $lowStock,
            'role_counts' => (new User())->countByRole(),
            'stats' => [
                'orders_count' => $counts['orders'],
                'products_count' => $counts['products'],
                'users_count' => $counts['users'],
                'paid_orders_count' => $paidOrders,
                'sales_total' => $sales,
            ],
        ];
    }

    private function globalCounts(): array
    {
        try {
            $products = (int)db()->query('SELECT COUNT(*) FROM products WHERE deleted_at IS NULL')->fetchColumn();
        } catch (Throwable $e) {
            $products = (int)db()->query('SELECT COUNT(*) FROM products')->fetchColumn();
        }
        return [
            'orders' => (int)db()->query('SELECT COUNT(*) FROM orders')->fetchColumn(),
            'products' => $products,
            'users' => (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn(),
        ];
    }

    private function salesLastSevenDays(): array
    {
        $series = [];
        for ($i = 6; $i >= 0; $i--) {
            $key = date('Y-m-d', strtotime("-$i days"));
            $series[$key] = 0.0;
        }

        $stmt = db()->prepare(
            "SELECT DATE(created_at) d, SUM(total_amount) t
             FROM orders
             WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
             GROUP BY DATE(created_at)"
        );
        $stmt->execute();
        foreach ($stmt->fetchAll() as $row) {
            $day = (string)($row['d'] ?? '');
            if ($day !== '' && array_key_exists($day, $series)) {
                $series[$day] = (float)($row['t'] ?? 0);
            }
        }

        $out = [];
        foreach ($series as $day => $value) {
            $out[] = [
                'day' => $day,
                'total' => $value,
            ];
        }
        return $out;
    }
}
