<?php

declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/TenantDB.php';

class Template
{
    public static function all(): array
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT * FROM templates WHERE company_id = ? ORDER BY created_at DESC');
        $stmt->execute([$companyId]);

        return $stmt->fetchAll();
    }

    public static function find(int $id): ?array
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT * FROM templates WHERE id = :id AND company_id = :company_id');
        $stmt->execute([':id' => $id, ':company_id' => $companyId]);
        $template = $stmt->fetch();

        return $template ?: null;
    }

    public static function create(array $data): int
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if ($companyId === null) {
            throw new RuntimeException('Company ID not available. Workspace context not properly initialized.');
        }
        
        $stmt = $pdo->prepare('INSERT INTO templates (name, header_html, footer_html, company_id, created_at) VALUES (:name, :header_html, :footer_html, :company_id, :created_at)');
        $stmt->execute([
            ':name' => $data['name'],
            ':header_html' => $data['header_html'] ?? null,
            ':footer_html' => $data['footer_html'] ?? null,
            ':company_id' => $companyId,
            ':created_at' => date('c'),
        ]);

        return (int) $pdo->lastInsertId();
    }

    public static function update(int $id, array $data): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('UPDATE templates SET name = :name, header_html = :header_html, footer_html = :footer_html WHERE id = :id AND company_id = :company_id');
        $stmt->execute([
            ':id' => $id,
            ':name' => $data['name'],
            ':header_html' => $data['header_html'] ?? null,
            ':footer_html' => $data['footer_html'] ?? null,
            ':company_id' => $companyId,
        ]);
    }

    public static function delete(int $id): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('DELETE FROM templates WHERE id = :id AND company_id = :company_id');
        $stmt->execute([':id' => $id, ':company_id' => $companyId]);
    }
}
