<?php

namespace Modules\Messaging\Controllers;

use App\Controllers\BaseController;
use App\Models\MessageConversationModel;
use App\Models\MessageParticipantModel;
use Modules\Messaging\Services\MessagingService;

class GroupController extends BaseController
{
    protected MessageConversationModel $conversations;
    protected MessageParticipantModel $participants;
    protected MessagingService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->conversations = new MessageConversationModel();
        $this->participants  = new MessageParticipantModel();
        $this->service       = new MessagingService();
    }

    public function index()
    {
        $groups = $this->conversations
            ->where('type', 'group')
            ->orderBy('name', 'ASC')
            ->findAll();

        foreach ($groups as &$g) {
            $g['member_count'] = $this->participants
                ->where('conversation_id', $g['id'])
                ->countAllResults();
        }
        unset($g);

        return view('Modules\Messaging\Views\groups\index', array_merge($this->baseViewData(), [
            'title'  => 'Message Groups',
            'groups' => $groups,
        ]));
    }

    public function createForm()
    {
        return view('Modules\Messaging\Views\groups\create', array_merge($this->baseViewData(), [
            'title'   => 'New Message Group',
            'group'   => [],
            'members' => [],
            'users'   => $this->service->listActiveUsers(),
        ]));
    }

    public function store()
    {
        $userId = (int) $this->session->get('user_id');
        $result = $this->service->createGroup($this->request->getPost(), $userId);

        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors'] ?? [])->with('error', $result['error'] ?? null);
        }

        return redirect()->to('/messages/groups')->with('success', 'Group created.');
    }

    public function editForm(int $id)
    {
        $group = $this->conversations->find($id);
        if (! $group || $group['type'] !== 'group') {
            return redirect()->to('/messages/groups')->with('error', 'Group not found.');
        }

        $members = $this->participants->getMembersWithNames($id);
        $memberIds = array_map(static fn ($m) => (int) $m['user_id'], $members);

        return view('Modules\Messaging\Views\groups\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Group',
            'group'     => $group,
            'members'   => $members,
            'memberIds' => $memberIds,
            'users'     => $this->service->listActiveUsers(),
        ]));
    }

    public function update(int $id)
    {
        $userId = (int) $this->session->get('user_id');
        $result = $this->service->updateGroup($id, $this->request->getPost(), $userId);

        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors'] ?? [])->with('error', $result['error'] ?? null);
        }

        return redirect()->to('/messages/groups')->with('success', 'Group updated.');
    }

    public function destroy(int $id)
    {
        $userId = (int) $this->session->get('user_id');
        $result = $this->service->deleteGroup($id, $userId);

        if (! $result['success']) {
            return redirect()->to('/messages/groups')->with('error', $result['error'] ?? 'Could not delete group.');
        }

        return redirect()->to('/messages/groups')->with('success', 'Group deleted.');
    }
}
