<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\WhatsAppTemplate;

class TemplateController extends Controller {
    public function index(): void {
        $templates = WhatsAppTemplate::all('created_at DESC');
        $this->render('templates/index', ['templates' => $templates]);
    }

    public function store(): void {
        $name = trim(Request::post('name', ''));
        $category = Request::post('category', 'MARKETING');
        $language = Request::post('language', 'en_US');
        $headerType = Request::post('header_type', 'NONE');
        $bodyText = trim(Request::post('body_text', ''));
        $footerText = trim(Request::post('footer_text', ''));

        if (empty($name) || empty($bodyText)) {
            Response::error('Template name and body text are required.');
        }

        // Standardize template name (lowercase and underscores)
        $cleanName = preg_replace('/[^a-z0-9_]/', '_', strtolower($name));

        $id = WhatsAppTemplate::create([
            'name'        => $cleanName,
            'category'    => $category,
            'language'    => $language,
            'header_type' => $headerType,
            'body_text'   => $bodyText,
            'footer_text' => $footerText ?: null,
            'status'      => 'APPROVED',
            'created_at'  => date('Y-m-d H:i:s')
        ]);

        if (Request::isAjax()) {
            Response::success(WhatsAppTemplate::find($id), 'Template created successfully');
        }
        Response::redirect('/templates');
    }

    public function delete(int $id): void {
        WhatsAppTemplate::delete($id);
        if (Request::isAjax()) {
            Response::success(null, 'Template deleted');
        }
        Response::redirect('/templates');
    }
}
