<?php

namespace App\Controllers;

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

abstract class BaseController extends Controller
{
    protected $session;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        helper(['form', 'url', 'html', 'text', 'logo', 'activity_log', 'teacher_identifier']);

        $lockFile = WRITEPATH . 'installed.lock';

        if (! file_exists($lockFile)) {
            $path = ltrim($request->getUri()->getPath(), '/');
            $skip = ['install', 'install/process', 'assets', 'css', 'js', 'images', 'uploads'];

            $isSkipped = false;
            foreach ($skip as $s) {
                if (str_starts_with($path, $s)) {
                    $isSkipped = true;
                    break;
                }
            }

            if (! $isSkipped) {
                $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                header("Location: {$scheme}://{$_SERVER['HTTP_HOST']}/install");
                exit;
            }
        }

        $this->session = service('session');
    }
}
