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

class TemplatesController extends Controller
{
    public function index(): void
    {
        require_permission('templates.view');
        $model = new Template();
        $editId = (int)($_GET['edit'] ?? 0);
        $editTemplate = $editId ? $model->find($editId) : null;
        $this->view('templates/index', [
            'templates' => $model->all(),
            'editTemplate' => $editTemplate,
            'templateEditorState' => $this->editorStateForTemplate($editTemplate),
        ]);
    }

    public function save(): void
    {
        require_permission('templates.manage');
        verify_csrf();
        try {
            $mediaPath = null;
            if (!empty($_FILES['media_file']['name'])) {
                $mediaPath = upload_file($_FILES['media_file'], ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx']);
            }
            $data = $_POST;
            $type = in_array((string)($data['type'] ?? ''), ['sms', 'email'], true) ? (string)$data['type'] : 'email';
            $data['type'] = $type;
            $data['body'] = $type === 'email'
                ? trim((string)($data['theme_body_html'] ?? $data['body'] ?? ''))
                : trim((string)($data['sms_body_text'] ?? $data['body'] ?? ''));
            if ($mediaPath) {
                $data['media_path'] = $mediaPath;
            }
            (new Template())->save($data);
            flash('success', 'Template saved successfully.');
        } catch (Throwable $e) {
            flash('error', $e->getMessage());
        }
        redirect('templates/index');
    }

    public function delete(): void
    {
        require_permission('templates.delete');
        $id = (int)($_GET['id'] ?? 0);
        if ($id) {
            (new Template())->delete($id);
            flash('success', 'Template deleted.');
        }
        redirect('templates/index');
    }

    private function editorStateForTemplate(?array $template): array
    {
        if (!$template) {
            return [];
        }
        return [
            'id' => (int)($template['id'] ?? 0),
            'name' => (string)($template['name'] ?? ''),
            'type' => (string)($template['type'] ?? 'email'),
            'subject' => (string)($template['subject'] ?? ''),
            'preview_text' => (string)($template['preview_text'] ?? ''),
            'theme_body_html' => (string)($template['theme_html'] ?? $template['body'] ?? ''),
            'theme_css' => (string)($template['theme_css'] ?? ''),
            'theme_json' => (string)($template['theme_json'] ?? ''),
            'theme_preset' => (string)($template['theme_preset'] ?? 'custom'),
            'sms_body_text' => (string)(($template['type'] ?? '') === 'sms' ? ($template['body'] ?? '') : ''),
            'media_path' => (string)($template['media_path'] ?? ''),
            'is_theme_template' => !empty($template['is_theme_template']),
        ];
    }
}
