<?php

namespace App\Controllers;

use App\Models\AuditLogModel;
use App\Models\ClientModel;
use CodeIgniter\HTTP\RedirectResponse;

class ClientController extends BaseController
{
    public function index(): string
    {
        $clients = (new ClientModel())->orderBy('nombre')->findAll();
        return view('clients/index', [
            'title' => 'Clientes',
            'clients' => $clients,
        ]);
    }

    public function create(): string
    {
        return view('clients/form', [
            'title' => 'Nuevo cliente',
            'client' => null,
        ]);
    }

    public function store(): RedirectResponse
    {
        $data = $this->payload();
        if (! $this->validateData($data, $this->rules())) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $id = (new ClientModel())->insert($data, true);
        (new AuditLogModel())->record('client', (int) $id, 'create', $data);

        return redirect()->to(site_url('clients'))->with('success', 'Cliente creado.');
    }

    public function edit(int $id): string
    {
        $client = (new ClientModel())->find($id);
        if ($client === null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        return view('clients/form', [
            'title' => 'Editar cliente',
            'client' => $client,
        ]);
    }

    public function update(int $id): RedirectResponse
    {
        $model = new ClientModel();
        $client = $model->find($id);
        if ($client === null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        $data = $this->payload();
        if (! $this->validateData($data, $this->rules())) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }
        $model->update($id, $data);
        (new AuditLogModel())->record('client', $id, 'update', $data);
        return redirect()->to(site_url('clients'))->with('success', 'Cliente actualizado.');
    }

    public function delete(int $id): RedirectResponse
    {
        (new ClientModel())->delete($id);
        (new AuditLogModel())->record('client', $id, 'delete');
        return redirect()->to(site_url('clients'))->with('success', 'Cliente eliminado.');
    }

    private function payload(): array
    {
        return [
            'nombre' => trim((string) $this->request->getPost('nombre')),
            'contrato' => trim((string) $this->request->getPost('contrato')) ?: null,
            'direccion' => trim((string) $this->request->getPost('direccion')) ?: null,
            'contacto_nombre' => trim((string) $this->request->getPost('contacto_nombre')) ?: null,
            'contacto_email' => trim((string) $this->request->getPost('contacto_email')) ?: null,
            'contacto_telefono' => trim((string) $this->request->getPost('contacto_telefono')) ?: null,
            'notas' => trim((string) $this->request->getPost('notas')) ?: null,
        ];
    }

    private function rules(): array
    {
        return [
            'nombre' => 'required|max_length[200]',
            'contacto_email' => 'permit_empty|valid_email|max_length[160]',
        ];
    }
}
