<?php

namespace App\Controllers;

use App\Models\OrganizationMembershipModel;
use App\Models\OrganizationModel;
use Config\App;
use Config\Services;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

abstract class BaseController extends Controller
{
    protected $helpers = ['url', 'form'];
    protected ?array $authUser = null;
    protected ?array $currentMembership = null;

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

        $appConfig = config(App::class);
        $session = session();
        $locale = $session->get('locale');

        if (! in_array($locale, $appConfig->supportedLocales, true)) {
            $locale = $appConfig->defaultLocale;
            $session->set('locale', $locale);
        }

        $request->setLocale($locale);

        $this->authUser = $session->get('auth_user');

        if ($this->authUser) {
            $membershipModel = new OrganizationMembershipModel();
            $organizationModel = new OrganizationModel();
            $memberships = $membershipModel->activeForUser((int) $this->authUser['id']);
            $currentOrgId = (int) ($session->get('current_organization_id') ?? 0);

            if ($currentOrgId > 0) {
                $this->currentMembership = $membershipModel->findActiveMembership((int) $this->authUser['id'], $currentOrgId);

                if (! $this->currentMembership && $this->isPlatformAdmin()) {
                    $organization = $organizationModel->find($currentOrgId);
                    if ($organization) {
                        $this->currentMembership = [
                            'organization_id' => $organization['id'],
                            'organization_name' => $organization['name'],
                            'organization_slug' => $organization['slug'],
                            'role' => 'admin',
                        ];
                    }
                }
            }

            if (! $this->currentMembership && $memberships !== []) {
                $this->currentMembership = $memberships[0];
                $session->set('current_organization_id', (int) $this->currentMembership['organization_id']);
            }

            Services::renderer()->setData([
                'authUser' => $this->authUser,
                'currentMembership' => $this->currentMembership,
                'availableMemberships' => $memberships,
                'isPlatformAdmin' => $this->isPlatformAdmin(),
            ], 'raw');
        }

        Services::renderer()->setData([
            'currentLocale' => $locale,
            'supportedLocales' => $appConfig->supportedLocales,
            'localeNames' => [
                'pt' => 'PT',
                'en' => 'EN',
                'es' => 'ES',
            ],
        ], 'raw');
    }

    protected function authUser(): ?array
    {
        return $this->authUser;
    }

    protected function isPlatformAdmin(): bool
    {
        return ($this->authUser['role'] ?? null) === 'admin';
    }

    protected function currentOrganizationId(): ?int
    {
        if (! $this->currentMembership) {
            return null;
        }

        return (int) $this->currentMembership['organization_id'];
    }

    protected function currentMembership(): ?array
    {
        return $this->currentMembership;
    }

    protected function requireOrganizationContext()
    {
        if ($this->currentMembership) {
            return null;
        }

        return redirect()->to(site_url('organizations'))->with('error', 'Seleciona primeiro a empresa ativa.');
    }

    protected function canManageOrganization(): bool
    {
        if ($this->isPlatformAdmin()) {
            return true;
        }

        return in_array($this->currentMembership['role'] ?? '', ['owner', 'admin'], true);
    }

    protected function canManageOperations(): bool
    {
        if ($this->isPlatformAdmin()) {
            return true;
        }

        return in_array($this->currentMembership['role'] ?? '', ['owner', 'admin', 'manager'], true);
    }
}