<?php

class ACMS_POST_Form_Duplicate extends ACMS_POST_Form
{
    public function post()
    {
        $formId = intval($this->Get->get('fmid')) ?: null;

        $this->Post->setMethod('form', 'operative', $this->formAuthorization()->canEdit((int) SUID, BID));
        $this->Post->setMethod('form', 'fmidIsNull', $formId);
        $this->Post->validate(new ACMS_Validator());

        if ($this->Post->isValidAll()) {
            $form = $this->findFormById($formId);
            $newId = $this->formRepository()->duplicate(
                (int)$formId,
                BID,
                config('form_code_duplicate_suffix'),
                config('form_name_duplicate_suffix')
            );

            AcmsLogger::info('「' . $form['name'] . '（' . $form['code'] . '）」フォームを複製しました', [
                'sourceFormId' => $formId,
                'createdFormId' => $newId,
            ]);

            $url = acmsLink([
                'bid' => BID,
                'admin' => 'form_edit',
                'query' => [
                    'fmid' => $newId,
                    'edit' => 'update',
                ],
            ]);
            $this->redirect($url);
        } else {
            AcmsLogger::info('フォームの複製に失敗しました', [
                'fmid' => $formId,
            ]);
        }
        return $this->Post;
    }
}
