<?php



class ContactFormEmployee extends Form {

    function __construct($controller, $name) {

        // Create fields
        $file_validator = new Upload_Validator();
        $file_validator->setAllowedExtensions(array('doc','docx','pdf', 'rtf', 'jpg', 'jpeg', 'gif', 'png'));
        //$cvfield = new FileField('Cvfield', _t('LangEditor.CVFORM_CV', 'Jūsų CV', null, null, null, 'cvtemp'));
        $cvfield = new FileField('Cvfield', _t('LangEditor.CVFORM_CV', 'Jūsų CV'), null, null, null, 'cvtemp');
        $cvfield->setValidator($file_validator);

        $cities = ContactCities::get("ContactCities", "ContactPageEmployeeId = $controller->ID AND Active='1'", false);
        // Create fields
        $fields = new FieldSet(
                        new TextField('Name', _t('LangEditor.CONTACTFORM_NAME', 'Vardas, Pavardė')),
                        new EmailField('Email', _t('LangEditor.CONTACTFORM_EMAIL', 'El. paštas')),
                        new TextField('Phone', _t('LangEditor.CONTACTFORM_PHONE', 'Telefonas')),
                        new DropdownField(
                                'City',
                                'City',
                                $cities->map("ID", "Title", _t('LangEditor.CONTACTFORM_CITY_DEFAULT', 'Pasirinkite artimiausią miestą'))
                        ),
                        $cvfield,
                        new CaptchaField('SecurityCode', _t('LangEditor.CONTACTFORM_SECURITYCODE', 'Saugos kodas')),
                        new TextareaField('Comments', _t('LangEditor.CONTACTFORM_COMMENT_EMPLOYEE', 'Komentaras'))
        );

        // Create action
        $actions = new FieldSet(
                        new FormAction('SendContactForm', _t('LangEditor.CONTACTFORM_SEND', 'Siųsti'))
        );

        // Create Validators
        $validator = new RequiredFields('Name', 'Email', 'SecurityCode');

        parent::__construct($controller, $name, $fields, $actions, $validator);
    }

    function forTemplate() {
        return $this->renderWith(array(
                    $this->class,
                    'Form'
                ));
    }

    function SendContactForm($data, $form) {

        $settings = ContactPageEmployee::get_one('ContactPageEmployee', '', false);
        $to = $settings->Mailto;
        if(!empty($data['City']) && (int)$data['City']>0) {
            $city = DataObject::get_by_id('ContactCities', (int)$data['City']);
            if($city && !empty($city->Email)) {
                $to = $city->Email;
            }
        }

        $securityID = Session::get('SecurityID');
        $securityCode = Session::get('verifycode');

        if($securityID== $data['SecurityID']) {
            if($securityCode != $data['SecurityCode']){
                $form->addErrorMessage('SecurityCode', _t('LangEditor.CONTACTFORM_ERRSECURITYCODE', 'Apsaugos kodas nesutampa su žemiau esančiu'), 'bad');
                $form->sessionMessage(_t('LangEditor.CONTACTFORM_ERRSECURITYCODE', 'Apsaugos kodas nesutampa su žemiau esančiu'), 'bad');
                Director::redirectBack();
                return false;
            }
            //Set data
            $From = $data['Email'];

            $Subject = _t('LangEditor.CONTACTFORMEMPLOYEE_SUBJECT', 'Darbuotojų skiltis');

            $data['CityTitle'] = ($city) ? $city->Title : '';
            $data['CityID'] = (int)$data['City'];

            //
            $data['Date'] = date('Y-m-d H:i:s');
            $data['IP'] = $_SERVER['REMOTE_ADDR'];
            //

            $email = new Email('no-reply@webserver8.balt.net', $to, $Subject);
			$email->replyTo($From);
            //set template
            $email->setTemplate('ContactEmployeeEmail');
            //populate template
            $email->populateTemplate($data);

            // thats the tricky part for the files attaced
            if (isset($_FILES["Cvfield"]) && is_uploaded_file($_FILES["Cvfield"]["tmp_name"])) {
                $email->attachFile($_FILES["Cvfield"]["tmp_name"], $_FILES["Cvfield"]["name"]);
            }

            //send mail
            $email->send();
            //return to submitted message

            $item = new ContactEmployeeData($data);
            $item->write();

            Session::set('ActionStatus', 'success');
            Session::set('ActionMessage', _t('LangEditor.CONTACTFORM_SUCCESS', 'Ačiū, Jūsų žinutė sėkmingai išsiųsta. Netrukus su Jumis susisieksime.'));
        }
        Director::redirectBack();
    }
}

class ContactPageEmployee extends Page {

    static $db = array(
        'Mailto' => 'Varchar(100)',
        //'SubmitText' => 'Text'
    );
    static $has_one = array(
    );

    static $has_many = array (
        'City' => 'ContactCities',
    );

    function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab("Root.Content.OnSubmission", new TextField('Mailto', 'Email submissions to'));

        $fields->addFieldToTab("Root.Content.Cities", new DataObjectManager(
                $this,
                'City',
                'ContactCities',
                array(
                    'Title' => 'City',
                    'Email' => 'Email',
                    'Active' => 'Active?'),
                'getCMSFields_forPopup'
        ));
        //$fields->addFieldToTab("Root.Content.OnSubmission", new TextareaField('SubmitText', 'Text on Submission'));
        return $fields;
    }

}

class ContactPageEmployee_Controller extends Page_Controller {

    static $allowed_actions = array(
        'ContactFormEmployee'
    );

    function init() {
        parent::init();

        // Requirements::javascriptTemplate(MODULE_CONTACT_DIR . '/javascript/contactformemployee.js', array());

    }

    function ContactFormEmployee() {
        return new ContactFormEmployee($this, 'ContactFormEmployee');
    }

}
