<?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;
        $templates = $model->all();
        $this->view('templates/index', [
            'templates' => $templates,
            'editTemplate' => $editTemplate,
            'templateEditorState' => $this->editorStateForTemplate($editTemplate),
            'templateLibraryStats' => $this->libraryStats($templates),
        ]);
    }

    public function library(): void
    {
        require_permission('templates.view');
        $model = new Template();
        $templates = $model->all();
        $this->view('templates/library', [
            'templates' => $templates,
            'templateLibraryStats' => $this->libraryStats($templates),
        ]);
    }

    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/library');
    }


    public function uploadImage(): void
    {
        require_permission('templates.manage');
        if (!$this->isPost()) {
            $this->json(['ok' => false, 'error' => 'Method not allowed.'], 405);
        }
        verify_csrf();

        try {
            if (empty($_FILES['image_file']['name'])) {
                throw new RuntimeException('Choose an image to upload first.');
            }
            $filename = upload_file($_FILES['image_file'], ['jpg', 'jpeg', 'png', 'gif', 'webp']);
            $relativePath = 'uploads/' . $filename;
            $this->json([
                'ok' => true,
                'file' => $filename,
                'path' => $relativePath,
                'url' => full_url($relativePath),
            ]);
        } catch (Throwable $e) {
            $this->json(['ok' => false, 'error' => $e->getMessage()], 422);
        }
    }

    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/library');
    }

    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']),
        ];
    }

    private function libraryStats(array $templates): array
    {
        $stats = [
            'total' => count($templates),
            'email' => 0,
            'sms' => 0,
            'theme' => 0,
        ];

        foreach ($templates as $template) {
            $type = (string)($template['type'] ?? 'email');
            if ($type === 'sms') {
                $stats['sms']++;
            } else {
                $stats['email']++;
            }
            if (!empty($template['is_theme_template'])) {
                $stats['theme']++;
            }
        }

        return $stats;
    }
}
