<?php
declare(strict_types=1);

namespace App\Modules\Admin;

use App\Core\Database;
use App\Core\Request;
use App\Core\View;

final class AdminDashboardController
{
    public function index(Request $request): string
    {
        require_role('admin');

        $stats = [
            'total_users' => (int) Database::query('SELECT COUNT(*) AS total FROM users')->fetch()['total'],
            'total_clients' => (int) Database::query('SELECT COUNT(*) AS total FROM users WHERE role = :role', [
                'role' => 'client',
            ])->fetch()['total'],
            'total_products' => (int) Database::query('SELECT COUNT(*) AS total FROM products')->fetch()['total'],
            'total_purchases' => (int) Database::query('SELECT COUNT(*) AS total FROM purchases')->fetch()['total'],
            'pending_purchases' => (int) Database::query('SELECT COUNT(*) AS total FROM purchases WHERE status = :status', [
                'status' => 'pending',
            ])->fetch()['total'],
            'verified_purchases' => (int) Database::query('SELECT COUNT(*) AS total FROM purchases WHERE status = :status', [
                'status' => 'verified',
            ])->fetch()['total'],
            'completed_purchases' => (int) Database::query('SELECT COUNT(*) AS total FROM purchases WHERE status = :status', [
                'status' => 'completed',
            ])->fetch()['total'],
            'rejected_purchases' => (int) Database::query('SELECT COUNT(*) AS total FROM purchases WHERE status = :status', [
                'status' => 'rejected',
            ])->fetch()['total'],
        ];

        $recentUsers = Database::query(
            'SELECT nama, email, whatsapp, role, created_at
             FROM users
             ORDER BY created_at DESC, id DESC
             LIMIT 5'
        )->fetchAll();

        $recentPurchases = Database::query(
            'SELECT p.id, p.status, p.harga, p.created_at,
                    u.nama AS user_name,
                    pr.nama_produk AS product_name
             FROM purchases p
             INNER JOIN users u ON u.id = p.user_id
             INNER JOIN products pr ON pr.id = p.product_id
             ORDER BY p.created_at DESC, p.id DESC
             LIMIT 5'
        )->fetchAll();

        return View::renderTemplate('admin/dashboard', [
            'stats' => $stats,
            'recentUsers' => $recentUsers,
            'recentPurchases' => $recentPurchases,
        ], 'admin/layout');
    }
}
