<?php

namespace App\Http\Controllers\Admin\Config\Register;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Config;

class TossController extends Controller
{
    private Config $configModel;

    public function __construct(Config $config)
    {
        $this->configModel = $config;
    }

    /**
     * 토스 인증
     * @method GET
     * @see /admin/config/register/toss
     */
    public function index()
    {
        return view('admin.config.register.toss', [
            'config' => $this->configModel->getAllMeta()
        ]);
    }

    /**
     * 토스 인증 저장
     * @method POST
     * @see /admin/config/register/toss
     */
    public function store(Request $request)
    {
        $rules = [
            'toss_cert_is_test' => 'numeric|nullable|in:0,1',
            'live_toss_cert_client_id' => 'required_if:toss_cert_is_test,0|string|max:255',
            'live_toss_cert_client_secret' => 'required_if:toss_cert_is_test,0|string|max:255',
            'test_toss_cert_client_id' => 'required_if:toss_cert_is_test,1|string|max:255',
            'test_toss_cert_client_secret' => 'required_if:toss_cert_is_test,1|string|max:255',
        ];

        $attributes = [
            'toss_cert_is_test' => '실 토스 인증 여부',
            'live_toss_cert_client_id' => 'Live Client Key',
            'live_toss_cert_client_secret' => 'Live client Secret',
            'test_toss_cert_client_id' => 'Test Client Key',
            'test_toss_cert_client_secret' => 'Test Client Secret'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);

        $this->configModel->save($posts, $attributes);

        $message = '토스 인증서가 저장되었습니다.';
        return redirect()->route('admin.config.register.toss.index')->with('message', $message);
    }
}
