<?php
declare(strict_types=1);

namespace App\Modules\PublicArea;

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

final class ClientDashboardController
{
    public function index(Request $request): string
    {
        require_auth();

        if (Auth::role() === 'admin') {
            redirect('/admin/dashboard');
        }

        require_role('client');

        $user = Auth::user();
        $userId = (int) ($user['id'] ?? 0);

        $summary = Database::query(
            'SELECT
                COUNT(*) AS total_purchases,
                COALESCE(SUM(CASE WHEN status = :pending THEN 1 ELSE 0 END), 0) AS pending_purchases,
                COALESCE(SUM(CASE WHEN status = :verified THEN 1 ELSE 0 END), 0) AS verified_purchases,
                COALESCE(SUM(CASE WHEN status = :completed THEN 1 ELSE 0 END), 0) AS completed_purchases
             FROM purchases
             WHERE user_id = :user_id',
            [
                'user_id' => $userId,
                'pending' => 'pending',
                'verified' => 'verified',
                'completed' => 'completed',
            ]
        )->fetch() ?: [];

        $products = Database::query(
            'SELECT id, nama_produk, harga, deskripsi, status
             FROM products
             WHERE status = :status
             ORDER BY harga ASC, id ASC',
            [
                'status' => 'aktif',
            ]
        )->fetchAll();

        $recentPurchase = Database::query(
            'SELECT p.id, p.harga, p.status, p.created_at, p.updated_at,
                    pr.nama_produk AS product_name
             FROM purchases p
             INNER JOIN products pr ON pr.id = p.product_id
             WHERE p.user_id = :user_id
             ORDER BY p.created_at DESC, p.id DESC
             LIMIT 1',
            [
                'user_id' => $userId,
            ]
        )->fetch();

        return View::renderTemplate('public/dashboard', [
            'user' => $user,
            'products' => $products,
            'recentPurchase' => is_array($recentPurchase) ? $recentPurchase : null,
            'summary' => [
                'total_purchases' => (int) ($summary['total_purchases'] ?? 0),
                'pending_purchases' => (int) ($summary['pending_purchases'] ?? 0),
                'verified_purchases' => (int) ($summary['verified_purchases'] ?? 0),
                'completed_purchases' => (int) ($summary['completed_purchases'] ?? 0),
            ],
        ], 'public/client/layout');
    }
}
