<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Setup extends cf_base_controller
{
    private const COOKIE_SETUP_SESSION_ID_KEY = 'setup_session_id';
    public function __construct()
    {
        parent::__construct();
        $this->config->load('ion_auth', true);
        $this->load->model('setup_model');

        if ($this->setup_model->isSetupComplete()) {
            redirect('/', 'refresh');
            exit();
        }
        $this->data['title'] = 'Complete Setup';
        $this->data['minPasswordLength'] =
            Settings_rest_model::DEFAULT_FIELDS[Settings_rest_model::MIN_PASSWORD_LENGTH];
        $this->data['passwordComplexity'] =
            Settings_rest_model::DEFAULT_FIELDS[Settings_rest_model::PASSWORD_COMPLEXITY];
    }

    public function index()
    {
        $this->load->view('setup/root', $this->data);
    }

    public function complete()
    {
        $this->load->view('setup/root', $this->data);
    }

    public function validate_code()
    {
        $data = $this->getRequestBody();
        $apiResponse = $this->setup_model->validateCode($data['code'] ?? null);
        if ($apiResponse['isValid']) {
            set_cookie(
                name: self::COOKIE_SETUP_SESSION_ID_KEY,
                value: $apiResponse['sessionId'],
                expire: 3600,
                secure: true,
                httponly: true,
            );
            unset($apiResponse['sessionId']);
        }
        $this->output->set_content_type('application/json')->set_output(json_encode($apiResponse));
    }

    public function complete_setup()
    {
        $data = $this->getRequestBody();
        $data['sessionId'] = get_cookie(self::COOKIE_SETUP_SESSION_ID_KEY);
        $apiResponse = $this->setup_model->completeSetup($data);
        if ($apiResponse['success']) {
            $this->ion_auth->login($data['username'], $data['password'], boolval($data['remember']));
        }
        $this->output->set_content_type('application/json')->set_output(json_encode($apiResponse));
    }

    private function getRequestBody()
    {
        return json_decode(file_get_contents('php://input'), true);
    }
}
