<?php

class CaptchaField extends TextField {
    function validate($validator){
        if(!empty($this->value)){
            $SecurityCode = Session::get('verifycode');
            if($SecurityCode != $this->value){
                $validator->validationError(
                    $this->name,
                    _t('LangEditor.CONTACTFORM_ERRSECURITYCODE', 'Apsaugos kodas nesutampa su žemiau esančiu'),
                    'validation',
                    false
                );

                return false;
            }

            return true;
        }
    }
}

class ContactForm extends Form {

    function __construct($controller, $name) {

        // 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 TextField('Company', _t('LangEditor.CONTACTFORM_COMPANY', 'Įmonė')),
                        new TextareaField('Comments', _t('LangEditor.CONTACTFORM_COMMENT', 'Komentaras')),
                        new CaptchaField('SecurityCode', _t('LangEditor.CONTACTFORM_SECURITYCODE', 'Saugos kodas'))
        );

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

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

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

    function sendPost($firstName, $lastName, $phone, $email, $organization, $comment) {
            $service_url = 'https://api.insight.ly/v2.2/Leads';
            $ch = curl_init($service_url);

            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Authorization: Basic ' . base64_encode('db7f06b9-1d5d-433b-8811-bf32fc614c79')
            ));

            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

            $data = '{
                "FIRST_NAME": "'.$firstName.'",
                "LAST_NAME": "'.$lastName.'",
                "organization_name": "'.$organization.'",
                "mobile_phone_number": "'.$phone.'",
                "email_address": "'.$email.'",
                "Service_Country_L__c": "'.$lastName.'",
                "CUSTOMFIELDS": [ {
                    "CUSTOM_FIELD_ID": "Service_Country_L__c",
                    "FIELD_VALUE": "'.$lastName.'"
                    },
                    {
                    "CUSTOM_FIELD_ID": "Comments_L__c",
                    "FIELD_VALUE": "'.$comment.'"
                    },
                ]
            }';
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $return = curl_exec($ch);
            $err = curl_errno($ch);
            $msg = curl_error($ch);
            curl_close($ch);
   }


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

    function SendContactForm($data, $form) {

		$securityID = Session::get('SecurityID');
        $securityCode = Session::get('verifycode');
		$controller = Controller::curr();
        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;
            }

            $settings = ContactPage::get_one('ContactPage', '', false);

			//Set data
			$From = $data['Email'];
			$To = $controller->Mailto ? $controller->Mailto : $settings->Mailto;

			$Subject = _t('LangEditor.CONTACTFORM_SUBJECT', 'WEB kontaktų forma');

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

            // Send data to insigtly
            $this->sendPost($data['Name'], 'Biuro Lithuania', $data['Phone'], $data['Email'], $data['Company'], $data['Comments']);

			$email = new Email('no-reply@webserver8.balt.net', $To, $Subject);
			$email->replyTo($From);
			//set template
			$email->setTemplate('ContactEmail');
			//populate template
			$email->populateTemplate($data);
			//send mail
			$email->send();
			//return to submitted message

			$item = new ContactData($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 ContactPage extends Page {

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

    static $has_many = array (
    );

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

        $fields->addFieldToTab("Root.Content.OnSubmission", new TextField('Mailto', 'Email submissions to'));
        //$fields->addFieldToTab("Root.Content.OnSubmission", new TextareaField('SubmitText', 'Text on Submission'));
        return $fields;
    }

}

class ContactPage_Controller extends Page_Controller {

    static $allowed_actions = array(
        'ContactForm'
    );

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

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

    }

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

}
