#include "formtemplateeditor.h"
#include "ui_formtemplateeditor.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMessageBox>
#include <QDebug>

formTemplateEditor::formTemplateEditor(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::formTemplateEditor)
{
    ui->setupUi(this);
    connectSignals();
}

formTemplateEditor::~formTemplateEditor()
{
    delete ui;
}

void formTemplateEditor::connectSignals()
{
    connect(ui->saveButton, &QPushButton::clicked, this, &formTemplateEditor::saveTemplate);
}

void formTemplateEditor::loadTemplate(const Template &tpl)
{
    m_currentTemplate = tpl;
    ui->nameEdit->setText(tpl.name);
    ui->descriptionEdit->setText(tpl.description);
    ui->typeCombo->setCurrentText(tpl.documentType);
    ui->widthSpin->setValue(tpl.widthMM);
    ui->heightSpin->setValue(tpl.heightMM);
    ui->marginTopSpin->setValue(tpl.marginTop);
    ui->marginBottomSpin->setValue(tpl.marginBottom);
    ui->marginLeftSpin->setValue(tpl.marginLeft);
    ui->marginRightSpin->setValue(tpl.marginRight);
}

QJsonDocument formTemplateEditor::buildJSON()
{
    QJsonObject root;
    root["name"] = ui->nameEdit->text();
    root["description"] = ui->descriptionEdit->text();
    root["documentType"] = ui->typeCombo->currentText();
    root["widthMM"] = ui->widthSpin->value();
    root["heightMM"] = ui->heightSpin->value();
    root["margin"] = QJsonArray{
        ui->marginTopSpin->value(),
        ui->marginRightSpin->value(),
        ui->marginBottomSpin->value(),
        ui->marginLeftSpin->value()
    };
    root["elements"] = QJsonArray(); // Elements added by Canvas widget (placeholder)

    return QJsonDocument(root);
}

void formTemplateEditor::saveTemplate()
{
    QJsonDocument doc = buildJSON();
    QString content = QString::fromUtf8(doc.toJson());

    Template tpl;
    tpl.name = ui->nameEdit->text();
    tpl.description = ui->descriptionEdit->text();
    tpl.documentType = ui->typeCombo->currentText();
    tpl.widthMM = ui->widthSpin->value();
    tpl.heightMM = ui->heightSpin->value();
    tpl.marginTop = ui->marginTopSpin->value();
    tpl.marginBottom = ui->marginBottomSpin->value();
    tpl.marginLeft = ui->marginLeftSpin->value();
    tpl.marginRight = ui->marginRightSpin->value();
    tpl.content = content;
    tpl.isDefault = false;
    tpl.createdBy = "user";

    bool ok;
    if (m_currentTemplate.id > 0) {
        tpl.id = m_currentTemplate.id;
        ok = TemplateDAO::update(tpl);
    } else {
        ok = TemplateDAO::create(tpl);
    }

    if (ok) {
        QMessageBox::information(this, tr("Éxito"), tr("Plantilla guardada correctamente."));
        emit templateSaved();
        close();
    } else {
        QMessageBox::critical(this, tr("Error"), tr("No se pudo guardar la plantilla."));
    }
}