<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TypingJobSubmission;
use App\Models\User;
use App\Support\TypingJobSettings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\View\View;

class TypingJobSettingsAdminController extends Controller
{
    public function edit(Request $request): View
    {
        $tableAvailable = Schema::hasTable('typing_job_submissions');
        $summary = $tableAvailable
            ? [
                'total_tasks' => (int) TypingJobSubmission::query()->count(),
                'total_earned' => (float) TypingJobSubmission::query()->sum('reward_amount'),
                'total_members' => (int) User::query()->whereHas('typingJobSubmissions')->count(),
            ]
            : [
                'total_tasks' => 0,
                'total_earned' => 0.0,
                'total_members' => 0,
            ];

        return view('admin.typing_job.settings', [
            'definitions' => TypingJobSettings::definitions(),
            'values' => TypingJobSettings::inputValues(),
            'mechanics' => TypingJobSettings::mechanics(),
            'contentPreview' => TypingJobSettings::content(),
            'operatorOptions' => TypingJobSettings::operatorModeOptions(),
            'summary' => $summary,
            'tableAvailable' => $tableAvailable,
            'canViewHistory' => (bool) ($request->user('admin')?->hasAnyProjectPermission(['typing_job', 'typing_job_history']) ?? true),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $data = $request->validate(TypingJobSettings::validationRules());
        TypingJobSettings::saveInputValues($data);

        return back()->with('success', 'Typing Job settings updated successfully.');
    }
}
