<?php

namespace SEOAIC;

use Exception;
use SEOAIC\helpers\WPTransients;

class Company
{
    const COMPANY_STATUS_KEY = 'seoaic_company_status';
    const CHURN_STATUS = 'churn';
    const STATUS_LIFETIME = 120; // seconds

    /**
     * Gets Company status from the backend server. Received value is cached for 2 min.
     * @param bool $force To get the actual value from the backend without caching
     * @return string
     */
    public static function getStatus(bool $force = false): string
    {
        if ($force) {
            return self::getStatusRemote();
        }

        $status = WPTransients::getCachedValue(self::COMPANY_STATUS_KEY);

        if (!$status) {
            $status = self::getStatusRemote();

            WPTransients::cacheValue(self::COMPANY_STATUS_KEY, $status, self::STATUS_LIFETIME);
        }

        return $status;
    }

    public static function getStatusRemote()
    {
        global $SEOAIC;

        $status = '';

        try {
            $result = $SEOAIC->curl->setMethodGet()->initWithReturn('/api/companies/cs_stage_check', [], false, true);
            $status = !empty($result['stage']) ? $result['stage'] : '';
        } catch (Exception $e) {

        }

        return $status;
    }

    public static function isChurned()
    {
        $status = self::getStatus();

        if (self::CHURN_STATUS == $status) {
            return true;
        }

        return false;
    }
}
