<?php
require_once __DIR__ . '/../Core.php';

class Template extends Model
{
    private const META_COMMENT_PATTERN = '/^\s*<!--AIO_THEME_META:([A-Za-z0-9+\/=]+)-->\s*/';

    public function all(?string $type = null): array
    {
        if ($type) {
            $stmt = $this->db->prepare('SELECT * FROM templates WHERE type = ? ORDER BY updated_at DESC');
            $stmt->execute([$type]);
            return $this->hydrateCollection($stmt->fetchAll());
        }
        return $this->hydrateCollection($this->db->query('SELECT * FROM templates ORDER BY updated_at DESC')->fetchAll());
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM templates WHERE id = ?');
        $stmt->execute([$id]);
        $row = $stmt->fetch() ?: null;
        return $row ? $this->hydrateTemplate($row) : null;
    }

    public function save(array $data): bool
    {
        $data = $this->normalizeForSave($data);
        if (!empty($data['id'])) {
            $stmt = $this->db->prepare('UPDATE templates SET name=?, type=?, subject=?, body=?, media_path=?, updated_at=NOW() WHERE id=?');
            return $stmt->execute([
                $data['name'],
                $data['type'],
                $data['subject'] ?? null,
                $data['body'],
                $data['media_path'] ?? null,
                $data['id'],
            ]);
        }

        $stmt = $this->db->prepare('INSERT INTO templates (name, type, subject, body, media_path) VALUES (?, ?, ?, ?, ?)');
        return $stmt->execute([
            $data['name'],
            $data['type'],
            $data['subject'] ?? null,
            $data['body'],
            $data['media_path'] ?? null,
        ]);
    }

    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare('DELETE FROM templates WHERE id = ?');
        return $stmt->execute([$id]);
    }

    public static function compileEmailThemeBody(string $html, string $css = '', string $themeJson = '', string $previewText = '', string $themePreset = 'custom'): string
    {
        $html = trim($html);
        $css = trim($css);
        $previewText = trim($previewText);
        $themeJson = trim($themeJson);
        $themePreset = trim($themePreset) !== '' ? trim($themePreset) : 'custom';

        $compiled = '';
        if ($previewText !== '') {
            $compiled .= '<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;visibility:hidden;mso-hide:all;">' . htmlspecialchars($previewText, ENT_QUOTES, 'UTF-8') . "</div>\n";
        }
        if ($css !== '') {
            $compiled .= "<style>\n" . $css . "\n</style>\n";
        }
        $compiled .= $html;

        $meta = [
            'version' => '16.5',
            'theme_preset' => $themePreset,
            'preview_text' => $previewText,
            'css' => $css,
            'html' => $html,
            'theme_json' => $themeJson,
        ];

        return '<!--AIO_THEME_META:' . base64_encode((string)json_encode($meta)) . "-->\n" . $compiled;
    }

    public static function parseStoredEmailBody(string $stored): array
    {
        $result = [
            'meta' => [],
            'compiled_html' => $stored,
            'html' => $stored,
            'css' => '',
            'theme_json' => '',
            'preview_text' => '',
            'theme_preset' => 'custom',
        ];

        if (!preg_match(self::META_COMMENT_PATTERN, $stored, $matches)) {
            return $result;
        }

        $compiled = preg_replace(self::META_COMMENT_PATTERN, '', $stored, 1) ?? $stored;
        $decoded = base64_decode((string)($matches[1] ?? ''), true);
        $meta = is_string($decoded) ? json_decode($decoded, true) : null;
        if (!is_array($meta)) {
            $result['compiled_html'] = $compiled;
            $result['html'] = $compiled;
            return $result;
        }

        $result['meta'] = $meta;
        $result['compiled_html'] = $compiled;
        $result['html'] = (string)($meta['html'] ?? $compiled);
        $result['css'] = (string)($meta['css'] ?? '');
        $result['theme_json'] = (string)($meta['theme_json'] ?? '');
        $result['preview_text'] = (string)($meta['preview_text'] ?? '');
        $result['theme_preset'] = (string)($meta['theme_preset'] ?? 'custom');
        return $result;
    }

    private function hydrateCollection(array $rows): array
    {
        return array_map(fn(array $row): array => $this->hydrateTemplate($row), $rows);
    }

    private function hydrateTemplate(array $row): array
    {
        if (($row['type'] ?? '') !== 'email') {
            $row['compiled_body'] = $row['body'];
            $row['raw_body'] = $row['body'];
            $row['theme_html'] = $row['body'];
            $row['theme_css'] = '';
            $row['theme_json'] = '';
            $row['preview_text'] = '';
            $row['theme_preset'] = '';
            $row['is_theme_template'] = false;
            return $row;
        }

        $parsed = self::parseStoredEmailBody((string)($row['body'] ?? ''));
        $row['raw_body'] = $row['body'];
        $row['compiled_body'] = $parsed['compiled_html'];
        $row['body'] = $parsed['compiled_html'];
        $row['theme_html'] = $parsed['html'];
        $row['theme_css'] = $parsed['css'];
        $row['theme_json'] = $parsed['theme_json'];
        $row['preview_text'] = $parsed['preview_text'];
        $row['theme_preset'] = $parsed['theme_preset'];
        $row['is_theme_template'] = !empty($parsed['meta']);
        return $row;
    }

    private function normalizeForSave(array $data): array
    {
        $data['name'] = trim((string)($data['name'] ?? ''));
        $data['type'] = in_array((string)($data['type'] ?? ''), ['sms', 'email'], true) ? (string)$data['type'] : 'email';
        $data['subject'] = trim((string)($data['subject'] ?? '')) ?: null;
        $data['body'] = trim((string)($data['body'] ?? ''));
        if ($data['name'] === '') {
            throw new RuntimeException('Template name is required.');
        }
        if ($data['body'] === '') {
            throw new RuntimeException($data['type'] === 'email' ? 'Email theme HTML cannot be empty.' : 'Template body cannot be empty.');
        }

        if ($data['type'] === 'email') {
            $data['body'] = self::compileEmailThemeBody(
                $data['body'],
                (string)($data['theme_css'] ?? ''),
                (string)($data['theme_json'] ?? ''),
                (string)($data['preview_text'] ?? ''),
                (string)($data['theme_preset'] ?? 'custom')
            );
        }

        return $data;
    }
}
