<?php

use Contao\Backend;

/**
 * Callbacks
 */
$GLOBALS['TL_DCA']['tl_form']['config']['onsubmit_callback'][] = array('tl_form_extended','updateFormSubmissionsSet');

/**
 * Selector
 */
$GLOBALS['TL_DCA']['tl_form']['palettes']['__selector__'][] = 'cc_save_submissions';

/**
 * Modify default palette
 */
$GLOBALS['TL_DCA']['tl_form']['palettes']['default'] = str_replace('storeValues','storeValues,cc_save_submissions', $GLOBALS['TL_DCA']['tl_form']['palettes']['default']);

/**
 * Subpalettes
 */
$GLOBALS['TL_DCA']['tl_form']['subpalettes']['cc_save_submissions'] = 'cc_delete_after,cc_anonymise_after';


/**
 * Add fields to tl_content
 */
$GLOBALS['TL_DCA']['tl_form']['fields']['cc_save_submissions'] = array
    (
    'label' => &$GLOBALS['TL_LANG']['tl_form']['cc_save_submissions'],
    'exclude' => true,
    'search' => true,
    'inputType' => 'checkbox',
    'eval' => array('submitOnChange'=>true),
    'sql' => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_form']['fields']['cc_delete_after'] = array(
    'label' => &$GLOBALS['TL_LANG']['tl_form']['cc_delete_after'],
    'inputType' => 'text',
    'eval' => array('tl_class' => 'clr w50','rgxp'=>'natural','maxlength'=>3,'mandatory'=>true),
    'default' => 0,
    'sql' => "varchar(3) NOT NULL default '0'"
);

$GLOBALS['TL_DCA']['tl_form']['fields']['cc_anonymise_after'] = array(
    'label' => &$GLOBALS['TL_LANG']['tl_form']['cc_anonymise_after'],
    'inputType' => 'text',
    'eval' => array('tl_class' => 'w50','rgxp'=>'natural','maxlength'=>3,'mandatory'=>true),
    'default' => 6,
    'sql' => "varchar(3) NOT NULL default '6'"
);


/**
 * classes
 */
class tl_form_extended extends Backend { 

	public function updateFormSubmissionsSet($dc) { 
        $result = $this->Database->prepare('SELECT id FROM tl_form_submissions_set WHERE form_id=?')
            ->execute($dc->id);

        // If exists
        if($result->numRows) {
	        $form = $this->Database->prepare('SELECT alias,title FROM tl_form WHERE id=?')
	            ->execute($dc->id);
       
            $this->Database->prepare("UPDATE tl_form_submissions_set SET form_alias=?,form_title=? WHERE form_id=?")
                ->execute($form->alias, $form->title, $dc->id);
        }
	}

}  