<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Database;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\EmailTemplateModel;
use App\Services\ActivityLogger;

final class EmailTemplateController extends BaseController
{
    public function index(Request $request): Response
    {
        $rows = (new EmailTemplateModel())->allWithBusinessLine($request->query('category'));

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($rows);
        }

        return $this->view('marketing/email-templates', [
            'title' => 'Email Templates',
            'activeNav' => 'email-templates',
            'breadcrumbs' => [['Home', 'dashboard'], ['Marketing', 'campaigns'], ['Email Templates', 'email-templates']],
            'rows' => $rows,
            'businessLines' => Database::connection()->query('SELECT id, name FROM business_lines ORDER BY name')->fetchAll(),
        ]);
    }

    public function show(Request $request, array $params): Response
    {
        $template = (new EmailTemplateModel())->find((int) $params['id']);

        return $template === null ? AjaxResponse::notFound() : AjaxResponse::success($template);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'name' => 'required|string|max:150',
            'category' => 'required|in:welcome,follow_up,birthday,re_engagement,newsletter,general',
            'subject' => 'required|string|max:255',
            'body_html' => 'required|string',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
        ]);

        $model = new EmailTemplateModel();
        $id = $model->insert($data, $this->currentUserId());
        ActivityLogger::record('email_template', $id, 'template_created', "Created template \"{$data['name']}\"", category: 'admin');

        return AjaxResponse::created($model->find($id), 'Template created.');
    }

    public function update(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, [
            'name' => 'required|string|max:150',
            'category' => 'required|in:welcome,follow_up,birthday,re_engagement,newsletter,general',
            'subject' => 'required|string|max:255',
            'body_html' => 'required|string',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
        ]);

        $id = (int) $params['id'];
        $model = new EmailTemplateModel();
        $model->update($id, $data, $this->currentUserId());
        ActivityLogger::record('email_template', $id, 'template_updated', 'Template updated', category: 'admin');

        return AjaxResponse::success($model->find($id), 'Template updated.');
    }

    public function destroy(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new EmailTemplateModel())->delete($id, $this->currentUserId());
        ActivityLogger::record('email_template', $id, 'template_deleted', 'Template deleted', category: 'admin');

        return AjaxResponse::success(null, 'Template deleted.');
    }
}
