<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Support\AdminSecuritySettings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

class SecurityCredentialController extends Controller
{
    public function edit(): View
    {
        return view('admin.security_credentials.edit', [
            'definitions' => AdminSecuritySettings::definitions(),
            'values' => AdminSecuritySettings::values(),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [
            'admin_sso_refs' => ['nullable', 'string', 'max:1000'],
            'finance_daily_pin' => ['nullable', 'string', 'max:255'],
            'balance_update_pin' => ['nullable', 'string', 'max:255'],
            'impersonate_key' => ['nullable', 'string', 'max:255'],
            'admin_edit_password' => ['nullable', 'string', 'max:255'],
            'clear_finance_daily_pin' => ['nullable', 'boolean'],
            'clear_balance_update_pin' => ['nullable', 'boolean'],
            'clear_impersonate_key' => ['nullable', 'boolean'],
            'clear_admin_edit_password' => ['nullable', 'boolean'],
            'current_admin_password' => ['required', 'string', 'max:255'],
        ]);

        if ($validator->fails()) {
            return back()
                ->withErrors($validator)
                ->withInput($request->except($this->passwordFields()));
        }

        $validated = $validator->validated();
        $admin = Auth::guard('admin')->user();

        if (!$admin || !Hash::check((string) $validated['current_admin_password'], (string) $admin->password)) {
            return back()
                ->withErrors(['current_admin_password' => 'সুপার এডমিন লগইন পাসওয়ার্ড সঠিক নয়।'])
                ->withInput($request->except($this->passwordFields()));
        }

        try {
            $changed = AdminSecuritySettings::saveFromInput($validated);
        } catch (\Throwable $e) {
            report($e);

            return back()
                ->withInput($request->except($this->passwordFields()))
                ->with('error', 'সেটিংস সেভ করা যায়নি। DB connection/settings table/migration চেক করুন।');
        }

        return redirect()
            ->route('admin.security-credentials.edit')
            ->with('success', count($changed) > 0
                ? 'সিকিউরিটি পাসওয়ার্ড/PIN আপডেট হয়েছে।'
                : 'কোনো নতুন সিকিউরিটি value দেওয়া হয়নি।');
    }

    /**
     * @return array<int, string>
     */
    private function passwordFields(): array
    {
        return [
            'finance_daily_pin',
            'balance_update_pin',
            'impersonate_key',
            'admin_edit_password',
            'current_admin_password',
        ];
    }
}
