<?php

namespace App\Controllers;

use App\Models\UserModel;
use App\Services\SupportService;

class SupportController extends BaseController
{
    public function index()
    {
        $userId = $this->userId();
        if ($userId === null) {
            return redirect()->to('/sign-in');
        }

        $support = new SupportService();
        $user    = $this->currentUser($userId);
        if ($user === null) {
            return redirect()->to('/sign-in');
        }

        $state  = $support->formState($user);
        $errors = [];
        if (! $state['categories_available']) {
            $errors['form']                = SupportService::MSG_NO_CATEGORIES;
            $errors['support_category_id'] = SupportService::MSG_NO_CATEGORIES;
        }

        return $this->formView($state, $errors);
    }

    public function submit()
    {
        $userId = $this->userId();
        if ($userId === null) {
            return redirect()->to('/sign-in');
        }

        $support = new SupportService();
        $result  = $support->submit($userId, (array) $this->request->getPost());
        if ($result['ok'] ?? false) {
            return redirect()->to('/support')->with('success', $result['message']);
        }

        $values = $result['values'] ?? $support->formState($this->currentUser($userId) ?? []);

        return $this->formView($values, $result['errors'] ?? []);
    }

    /**
     * @param array<string, mixed> $state
     * @param array<string, string> $errors
     */
    private function formView(array $state, array $errors = [])
    {
        return view('support/index', [
            'title'     => 'Contact Support',
            'activeNav' => 'menu',
            'state'     => $state,
            'errors'    => $errors,
        ]);
    }

    /**
     * @return array<string, mixed>|null
     */
    private function currentUser(int $userId): ?array
    {
        $row = (new UserModel())->find($userId);

        return $row === null ? null : $row;
    }

    private function userId(): ?int
    {
        $id = (int) session()->get('user_id');

        return $id > 0 ? $id : null;
    }
}
