<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\{Auth, Database, Response};
use App\Models\{BankAccount, CreatorBalance, CreatorLedger, Order, Setting, WithdrawalRequest};
use Throwable;

class EarningController extends BaseController
{
    public function summary(): Response
    {
        if (!Auth::check()) {
            return Response::json(['ok' => false, 'message' => 'Giris yapmalisin.'], 403);
        }

        try {
            $userId = (int) Auth::id();
            $settings = (new Setting())->getFinancialSettings();

            return Response::json([
                'ok' => true,
                'balance' => (new CreatorBalance())->findOrCreate($userId, (string) $settings['currency']),
                'sales' => (new Order())->recentSalesForCreator($userId, 30),
                'ledger' => (new CreatorLedger())->recentForUser($userId, 50),
                'withdrawals' => (new WithdrawalRequest())->listForUser($userId, 50),
                'bank_accounts' => (new BankAccount())->listForUser($userId),
                'settings' => $settings,
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'earning.summary');

            return Response::json(['ok' => false, 'message' => 'Kazanc bilgileri okunamadi.'], 500);
        }
    }

    public function zpanelSummary(): Response
    {
        Auth::requireAdmin();

        try {
            $orderModel = new Order();

            return Response::json([
                'ok' => true,
                'summary' => $orderModel->adminEarningSummary(),
                'creators' => $orderModel->creatorSummaries(100),
                'sales' => $orderModel->recentSalesForAdmin(50),
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'earning.zpanelSummary');

            return Response::json(['ok' => false, 'message' => 'Finans ozeti okunamadi.'], 500);
        }
    }

    public function zpanelLedger(): Response
    {
        Auth::requireAdmin();

        try {
            return Response::json([
                'ok' => true,
                'ledger' => (new CreatorLedger())->recentForAdmin((int) ($_GET['limit'] ?? 100)),
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'earning.zpanelLedger');

            return Response::json(['ok' => false, 'message' => 'Ledger kayitlari okunamadi.'], 500);
        }
    }
}
