<?php

namespace App\Controllers;

use App\Models\EventClientModel;
use App\Models\EventModel;

class EventClientController extends BaseController
{
    public function index()
    {
        $term  = trim((string) $this->request->getGet('q'));
        $model = new EventClientModel();

        $clients = $term !== ''
            ? $model->search($term)->orderBy('company_name')->findAll()
            : $model->orderBy('company_name')->findAll();

        return view('events/clients_index', [
            'pageTitle' => 'Event Clients',
            'clients'   => $clients,
            'term'      => $term,
        ]);
    }

    public function new()
    {
        return view('events/client_form', ['pageTitle' => 'New Event Client', 'client' => null]);
    }

    public function create()
    {
        $model = new EventClientModel();
        $data  = $this->collectInput();

        if (! $model->insert($data)) {
            return $this->redirectWithModelErrors($model);
        }

        $this->logActivity('events', 'Created event client "' . $data['company_name'] . '".');

        return redirect()->to('event-clients/' . $model->getInsertID())->with('success', 'Event client created.');
    }

    public function show(int $id)
    {
        $client = (new EventClientModel())->find($id);

        if ($client === null) {
            return redirect()->to('event-clients')->with('error', 'Event client not found.');
        }

        return view('events/client_show', [
            'pageTitle' => $client->company_name,
            'client'    => $client,
            'events'    => (new EventModel())->historyForClient($id),
        ]);
    }

    public function edit(int $id)
    {
        $client = (new EventClientModel())->find($id);

        if ($client === null) {
            return redirect()->to('event-clients')->with('error', 'Event client not found.');
        }

        return view('events/client_form', ['pageTitle' => 'Edit Event Client', 'client' => $client]);
    }

    public function update(int $id)
    {
        $model = new EventClientModel();

        if ($model->find($id) === null) {
            return redirect()->to('event-clients')->with('error', 'Event client not found.');
        }

        $data = $this->collectInput();

        if (! $model->update($id, $data)) {
            return $this->redirectWithModelErrors($model);
        }

        $this->logActivity('events', 'Updated event client "' . $data['company_name'] . '".');

        return redirect()->to('event-clients/' . $id)->with('success', 'Event client updated.');
    }

    /** Used by the new-event form to search for a company client inline. */
    public function lookup()
    {
        $term = (string) $this->request->getGet('q');

        if (trim($term) === '') {
            return $this->response->setJSON(['results' => []]);
        }

        $clients = (new EventClientModel())->search($term)->limit(10)->findAll();

        return $this->response->setJSON([
            'results' => array_map(static fn ($c) => ['id' => $c->id, 'company_name' => $c->company_name], $clients),
        ]);
    }

    private function collectInput(): array
    {
        return [
            'company_name'          => $this->request->getPost('company_name'),
            'contact_name'          => $this->request->getPost('contact_name') ?: null,
            'phone'                 => $this->request->getPost('phone') ?: null,
            'email'                 => $this->request->getPost('email') ?: null,
            'catering_preferences'  => $this->request->getPost('catering_preferences') ?: null,
        ];
    }
}
