<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ApiRequestLog;
use App\Models\Setting;
use App\Models\SecureCredential;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SystemController extends Controller
{
    public function settings(): View
    {
        $page_title = 'Sistem Ayarları';
        $page_description = 'Panel adı, marka, varsayılan para birimi ve zaman dilimi';
        $settings = Setting::where('group', 'general')->pluck('value', 'key');

        return view('admin.system.settings', compact('page_title', 'page_description', 'settings'));
    }

    public function saveSettings(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'panel_name' => ['nullable', 'string', 'max:255'],
            'agency_name' => ['nullable', 'string', 'max:255'],
            'default_currency' => ['nullable', 'string', 'size:3'],
            'default_timezone' => ['nullable', 'string', 'max:80'],
        ]);

        foreach ($data as $key => $value) {
            Setting::updateOrCreate(['group' => 'general', 'key' => $key], ['value' => $value]);
        }

        return back()->with('success', 'Sistem ayarları kaydedildi.');
    }

    public function logs(): View
    {
        $page_title = 'API / Sistem Logları';
        $page_description = 'API çağrıları ve hata kayıtları';
        $logs = ApiRequestLog::latest()->paginate(30);

        return view('admin.system.logs', compact('page_title', 'page_description', 'logs'));
    }

    public function queue(): View
    {
        $page_title = 'Cron / Queue Durumu';
        $page_description = 'Zamanlanmış görevlerin ilk kontrol ekranı';

        return view('admin.system.queue', compact('page_title', 'page_description'));
    }

    public function tokenVault(): View
    {
        $page_title = 'Token Kasası';
        $page_description = 'Şifreli saklanan API/OAuth bağlantı kayıtları';
        $credentials = SecureCredential::with('client')->latest()->paginate(30);

        return view('admin.system.token-vault', compact('page_title', 'page_description', 'credentials'));
    }
}
