<?php

namespace HS\Install\Updater\Updates\Tasks;

use HS\Install\Updater\Updates\BaseUpdate;

class HelpSpotFiveSessionLength extends BaseUpdate
{
    protected $version = '5.0.70';

    public function run()
    {
        // Create a cHD_SESSION_TIMEOUT setting if it does not already exist
        $sessionLength = $this->db->table('HS_Settings')
            ->where('sSetting', 'cHD_SESSION_TIMEOUT')
            ->first();

        if (! $sessionLength) {
            return $this->db->table('HS_Settings')
                ->insert([
                    'sSetting' => 'cHD_SESSION_TIMEOUT',
                    'tValue' => '86400', // Default to 1 day, 86400 seconds
                ]);
        }

        if (! is_numeric($sessionLength->tValue) || $sessionLength->tValue == 0) {
            $this->db->table('HS_Settings')
                ->where('sSetting', 'cHD_SESSION_TIMEOUT')
                ->update(['tValue' => '86400']); // Set to 1 day
        }

        // We no longer support session length over 1 year
        if ($sessionLength->tValue > 31536000) {
            $this->db->table('HS_Settings')
                ->where('sSetting', 'cHD_SESSION_TIMEOUT')
                ->update(['tValue' => '31536000']); // Set back to 1 year session timeout
        }
    }
}
