<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Models\Template;

class TemplateController extends BaseController
{
    /**
     * List all templates for the company
     */
    public function index(Request $request, Response $response)
    {
        $templateModel = new Template();
        $templates = $templateModel->findAllByCompany($request->company_id);
        
        $response->json([
            'status' => 'success',
            'data' => $templates
        ]);
    }

    /**
     * Store a new template
     */
    public function store(Request $request, Response $response)
    {
        $errors = $this->validate($request, [
            'name' => 'required',
            'body' => 'required'
        ]);

        if (!empty($errors)) {
            $response->status(400)->json(['status' => 'error', 'errors' => $errors]);
            return;
        }

        $body = $request->getBody();
        $templateModel = new Template();

        $id = $templateModel->createSecure([
            'company_id' => $request->company_id,
            'name' => $body['name'],
            'body' => $body['body'],
            'type' => $body['type'] ?? 'text',
            'media_url' => $body['media_url'] ?? null
        ]);

        $response->status(201)->json([
            'status' => 'success',
            'message' => 'Template created successfully',
            'id' => $id
        ]);
    }
}
