<?php

class Setup_model extends Cf_Model
{
    public const SETUP_URI = '/setup';
    public const SESSION_ID_HEADER = 'Cf-Setup-Session-Id';

    public function isSetupComplete()
    {
        $status = json_decode($this->getRestClient()->get(sprintf('%s/status', self::SETUP_URI)), associative: true);
        return $status['is_setup_complete'] ?? null;
    }

    public function validateCode($code)
    {
        try {
            $result = json_decode(
                $this->getRestClient()->post(sprintf('%s/code/validate', self::SETUP_URI), [
                    'code' => $code,
                ]),
                associative: true,
            );
        } catch (Exception $e) {
            $result = ['error' => $e->getMessage(), 'isValid' => false];
        }
        return $result;
    }

    public function completeSetup(array $data)
    {
        try {
            json_decode(
                $this->getRestClient()->post(sprintf('%s/complete', self::SETUP_URI), $data, [
                    self::SESSION_ID_HEADER => $data['sessionId'],
                ]),
                associative: true,
            );
            $result = ['error' => '', 'success' => true];
        } catch (Exception $e) {
            $result = ['error' => $e->getMessage(), 'success' => false];
        }
        return $result;
    }
}
