<?php

namespace App\Models;

use App\Core\Security;

/**
 * Template Model
 * Stores predefined WhatsApp message templates with variables.
 */
class Template extends BaseModel
{
    protected static string $table = 'templates';

    /**
     * Create template with encrypted media URL if exists
     */
    public static function createSecure(array $data)
    {
        if (!empty($data['media_url'])) {
            $data['media_url'] = Security::encrypt($data['media_url']);
        }
        return self::create($data);
    }

    /**
     * Retrieve and decrypt templates
     */
    public static function findAllByCompany(int $companyId)
    {
        $templates = \App\Core\Database::select(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id DESC",
            [$companyId]
        );

        foreach ($templates as &$template) {
            if (!empty($template['media_url'])) {
                $template['media_url'] = Security::decrypt($template['media_url']);
            }
        }

        return $templates;
    }
    
    /**
     * Get single template and decrypt
     */
    public static function findByIdAndCompany(int $id, int $companyId)
    {
        $template = \App\Core\Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE id = ? AND company_id = ? LIMIT 1",
            [$id, $companyId]
        );
        
        if ($template && !empty($template['media_url'])) {
            $template['media_url'] = Security::decrypt($template['media_url']);
        }
        
        return $template;
    }
}
