<?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);
        $this->view('templates/index', ['templates' => $model->all(), 'editTemplate' => $editId ? $model->find($editId) : null]);
    }

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