<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Validator;
use App\Models\AuditLog;
use App\Models\EmailTemplate;
use App\Services\MergeService;

final class TemplateController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('templates');
        $page = $this->page();
        $result = EmailTemplate::paginate($page, 20);
        $campaignCounts = EmailTemplate::campaignCounts();
        $rows = [];
        foreach ($result['rows'] as $r) {
            $hay = (string) ($r['subject'] ?? '') . ' ' . (string) ($r['body'] ?? '');
            $r['tags'] = MergeService::tagsIn($hay);
            $r['campaign_count'] = $campaignCounts[(int) $r['id']] ?? 0;
            $rows[] = $r;
        }
        view('marketing/templates', [
            'title' => 'Email templates',
            'rows' => $rows,
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / 20)),
            'counts' => EmailTemplate::boardCounts(),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('templates');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())->required($data, ['name' => 'Name', 'subject' => 'Subject', 'body' => 'Body']);
        if ($v->fails()) {
            $this->fail($v);
        }
        $id = EmailTemplate::create([
            'name' => mb_substr((string) $data['name'], 0, 150),
            'subject' => mb_substr((string) $data['subject'], 0, 180),
            'body' => MergeService::sanitizeBody((string) $data['body']),
            'created_by' => Auth::instance()->id(),
        ]);
        AuditLog::write('template.create', 'email_template', $id);
        json_out(['ok' => true, 'id' => $id]);
    }

    public function update(Request $request): void
    {
        $this->requireModule('templates');
        $this->verifyCsrf($request);
        $id = (int) $request->param('id');
        $row = EmailTemplate::find($id);
        if (!$row) {
            json_out(['ok' => false, 'error' => 'Not found.'], 404);
        }
        $data = $request->all();
        $v = (new Validator())->required($data, ['name' => 'Name', 'subject' => 'Subject', 'body' => 'Body']);
        if ($v->fails()) {
            $this->fail($v);
        }
        EmailTemplate::update($id, [
            'name' => mb_substr((string) $data['name'], 0, 150),
            'subject' => mb_substr((string) $data['subject'], 0, 180),
            'body' => MergeService::sanitizeBody((string) $data['body']),
        ]);
        json_out(['ok' => true]);
    }
}
