<?php

namespace App\Controllers;

use App\Helpers\UserHelper;
use App\Libraries\MyAuth\GoogleAuth;
use App\Libraries\MyAuth\LocalAuth;
use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
use App\Models\UserModel;
use CodeIgniter\HTTP\RedirectResponse;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use Psr\Log\LoggerInterface;

class UserController extends FrontController
{
    private $_model = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->class_name .= "User";
        $this->class_path .= $this->class_name;
        $this->title = lang("{$this->class_path}.title");
        $this->helper = new UserHelper();
    }
    protected function getModel(): UserModel
    {
        if ($this->_model === null) {
            $this->_model = new UserModel();
        }
        return $this->_model;
    }
    protected function setFormFieldRule($field, Validation $validation, string $action): Validation
    {
        switch ($field) {
            case 'role':
                //아래 Rule Array는 필드명.* checkbox를 사용
                $validation->setRule($field . ".*", $field, $this->getModel()->getFieldRule($action, $field));
                break;
            default:
                $validation = parent::setFormFieldRule($field, $validation, $action);
                break;
        }
        return $validation;
    }
    protected function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            default:
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    protected function getFormData(string $field, array $formDatas): array
    {
        switch ($field) {
            case 'role':
                $roles = $this->request->getVar($field) ?? [];
                if (!count($roles)) {
                    throw new \Exception("권한이 지정되지 않았습니다.");
                }
                $formDatas[$field] = implode(DEFAULTS["DELIMITER_ROLE"], $roles);
                break;
            default:
                $formDatas = parent::getFormData($field, $formDatas);
                break;
        }
        return $formDatas;
    }

    private function init(string $action): void
    {
        $this->action = $action;
        $this->fields = ['id', 'passwd'];
        $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields);
    }
    //로그인화면
    public function login_form(): RedirectResponse|string
    {
        $this->init('login');
        try {
            helper(['form']);
            //구글 로그인 BUTTON용
            $google_socket = new GoogleSocket();
            $this->google_url = $google_socket->createAuthUrl();
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return view(
                $this->view_path . "login",
                data: ['viewDatas' => $this->getViewDatas()]
            );
        } catch (\Exception $e) {
            log_message("error", $e->getMessage());
            return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
        }
    }
    //로그인처리
    public function login(): RedirectResponse|string
    {
        $this->init('login');
        try {
            $this->create_validate($this->action, $this->fields);
            $this->formDatas = $this->getFormDatas();
            $auth = new LocalAuth();
            $auth->login($auth->checkUser($this->formDatas));
            $this->message = "로그인 성공";
            log_message("notice", __FUNCTION__ . $this->message);
            // 이전 URL로 리다이렉트
            return redirect()->to($this->popPreviousUrl())->with('message', $this->message);
        } catch (\Exception $e) {
            log_message("error", $e->getMessage());
            return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
        }
    }
    public function google_login(): RedirectResponse|string
    {
        $this->init('login');
        try {
            $access_code = $this->request->getVar('code');
            if (!$access_code) {
                throw new \Exception("구글 로그인 실패");
            }
            $auth = new GoogleAuth();
            $auth->login($auth->checkUser($access_code));
            $this->message = "로그인 성공";
            log_message("notice", __FUNCTION__ . $this->message);
            // 이전 URL로 리다이렉트
            return redirect()->to($this->popPreviousUrl())->with('message', $this->message);
        } catch (\Exception $e) {
            log_message("error", $e->getMessage());
            return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
        }
    }
    //로그아웃
    public function logout(): RedirectResponse
    {
        try {
            $auth = new LocalAuth();
            $auth->logout();
            // 성공 메시지 설정
            $message = "로그아웃 되었습니다.";
            // 홈페이지로 리다이렉트
            return redirect()->route('/')->with('message', $message);
        } catch (\Exception $e) {
            log_message("error", $e->getMessage());
            return redirect()->back()->with('error', "로그아웃 중 오류가 발생했습니다.");
        }
    }
}
