<?php

use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Control\Director;
use SilverStripe\Control\Session;
use SilverStripe\View\Requirements;
use SilverStripe\Forms;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\RequiredFields;
use SilverStripe\Forms\FormAction;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Control\Email\Email;
use SilverStripe\View\ArrayData;

class PageController extends ContentController
{
    /**
     * An array of actions that can be accessed via a request. Each array element should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * [
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this action
     *     'action' => '->checkAction' // you can only access this action if $this->checkAction() returns true
     * ];
     * </code>
     *
     * @var array
     */
    private static $allowed_actions = ['ContactForm','doContactForm','ConnectForm','doConnectForm'];

   // private static $FilterData = [];
    
    protected function init()
    {
        parent::init();
        // You can include any CSS or JS required by your project here.
        // See: https://docs.silverstripe.org/en/developer_guides/templates/requirements/
        
        
       // Requirements::javascript("javascript/some_file.js");
        //Requirements::css("resources/themes/rssdixie/css/reset.css");
        Requirements::themedCss("reset");
        Requirements::themedCss("bootstrap.min");
        Requirements::themedCss("typography");
        Requirements::themedCss("layout");
        Requirements::themedCss("form");
        Requirements::themedCss("nav");
        Requirements::themedCss("mobile");
        Requirements::javascript('//code.jquery.com/jquery-1.12.4.min.js');
        Requirements::themedJavascript('bootstrap.min');
       // Requirements::css("resources/themes/rssdixie/css/bootstrap.min.css");
    //    Requirements::css("resources/themes/rssdixie/css/typography.css");
    //    Requirements::css("resources/themes/rssdixie/css/layout.css");
        
       //  Requirements::themedJavascript('script');
    }
    
    public function TopProducts(){
        $products = ProductPage::get();
        return $products;
    }
    
    public function TopIndustries(){
         $industries = IndustryPage::get();
        return $industries;
    }
    
    public function TopClients(){
        $clients = Client::get()->filter('Active',1)->sort('SortOrder');
        return $clients;
        
        
    }
    
    public function ContactForm(){
        $FirstNameField = TextField::create("FirstName","First Name");
        $LastNameField = TextField::create("LastName","Last Name");
       // $CompanyField = TextField::create("Company","Company");
        $EmailField = TextField::create("Email","Email");
        $CommentField = TextareaField::create('Comment', 'How can we help you?');
        
          $ThisFormFields = new FieldList(
 
			// List your fields here
                    $FirstNameField,$LastNameField, $EmailField,
                    $CommentField
                       
		);
        

		
		$ThisFormFieldsRequired = new RequiredFields(
                        
                    // List the required fields here: "Email", "FirstName"
                        'FirstName','LastName','Email'
 
		);

                $ActionButton = new FormAction("doContactForm", "Submit", 'Submit');
                $ActionButton->addExtraClass('button-alt'); 
                
		$ThisFormAction = new FieldList(
                        $ActionButton
			// List the action buttons here
			
 
		);
		
        $myForm = new Form($this, "ContactForm", $ThisFormFields, $ThisFormAction, $ThisFormFieldsRequired);

        return $myForm;
        
    }
    
    public function doContactForm($data, $form){
        $ContactData = new ContactDataModel();
     //   $ContactData->SubmissionType = $data['SubmissionType'];
 		$ContactData->FirstName = !empty($data['FirstName']) ? $data['FirstName'] : "";
        $ContactData->LastName = !empty($data['LastName']) ? $data['LastName'] : "";
        $ContactData->Email = !empty($data['Email']) ? $data['Email'] : "";
        $ContactData->Comment = !empty($data['Comment']) ? $data['Comment'] : "";
        
         //save the data
        $EmailData = $ContactData;
        $ContactData->write();

        $this->SendNotificationEmail($ContactData);
        $this->SendThankYouEmail($ContactData);
         //$form->sessionMessage('Successful!', 'good');
         //return $this->redirectBack();
        return $this->redirect('thank-you');
    }
    
    

    
    public function ConnectForm(){
        $request = Injector::inst()->get(HTTPRequest::class);
        $session = $request->getSession();
       $FilterData = $session->get("FilterForm");

        $FirstNameField = TextField::create("FirstName","First Name");
        $LastNameField = TextField::create("LastName","Last Name");
        $EmailField = TextField::create("Email","Email");
		$CompanyField = TextField::create("Company","Company");
        $PhoneField = TextField::create("Phone","Phone");
        
        //$AddressField = TextField::create("Address_1","Address");
		//$CityField = TextField::create("City","City");
		//$StateField = TextField::create("State","State");
		//$ZipField = TextField::create("Zip","Zip");
		//$ExistingCustomerField = CheckboxField::create("ExistingCustomer","Are you an existing customer?");
        
        $CommentField = TextareaField::create('Comment', 'How can we help you?');
        switch($FilterData){

            case 'ask-a-question':
                $NotificationRouter = 'info@rssdixie.com';
                $CommentField = TextareaField::create('Comment', 'How can we help you?');
                
                break;
            case 'order-product':
                $NotificationRouter = 'order@rssdixie.com';
               // $SamplesField = TextareaField::create('Samples', 'What sample panels would you like to order?');
                $CommentField = TextareaField::create('Comments', 'What products are you interested in?');
                break;
        }
      //  $NotificationEmailField = HiddenField::create('NotificationEmail','NotificationEmail', $NotificationRouter);

       
            $ThisFormFields = new FieldList(
 
			// List your fields here
                    $FirstNameField,$LastNameField, $EmailField,$PhoneField,
					$CompanyField,
                    $CommentField

                       
		);
        

		
		$ThisFormFieldsRequired = new RequiredFields(
                        
                    // List the required fields here: "Email", "FirstName"
                        'FirstName','LastName','Email','Phone'
 
		);
                //, "TransferEfficiency"
                $ActionButton = new FormAction("doConnectForm", "Submit", 'Submit');
                $ActionButton->addExtraClass('button-alt'); 
                
		$ThisFormAction = new FieldList(
                        $ActionButton
			// List the action buttons here
			
 
		);
		
        $myForm = new Form($this, "ConnectForm", $ThisFormFields, $ThisFormAction, $ThisFormFieldsRequired);
       // $myForm->setTemplate('ColorSearchForm');
   //     return $data ? $myForm->loadDataFrom($data) : $myForm;

       /* if (!empty($FilterData)){
            return $myForm;
        }else{
            return false;
        }*/
        return $myForm;
        
    }
    
public function doConnectForm($data, $form){
       global $emailConfig;

          $EmailData = "";



// $form->saveInto($submission);
       ///////////////////////////////////////////// SAVE AS CONTACT DATA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


            
            $ContactData = new ContactDataModel();
           // $ContactData->SubmissionType = $data['SubmissionType'];
 			$ContactData->FirstName = !empty($data['FirstName']) ? $data['FirstName'] : "";
            $ContactData->LastName = !empty($data['LastName']) ? $data['LastName'] : "";
            $ContactData->Email = !empty($data['Email']) ? $data['Email'] : "";
			$ContactData->Company = !empty($data['Company']) ? $data['Company'] : "";
            $ContactData->Phone = !empty($data['Phone']) ? $data['Phone'] : "";
            //$ContactData->Address_1 = !empty($data['Address_1']) ? $data['Address_1'] : "";
			//$ContactData->City = !empty($data['City']) ? $data['City'] : "";
			//$ContactData->State = !empty($data['State']) ? $data['State'] : "";
			//$ContactData->Zip = !empty($data['Zip']) ? $data['Zip'] : "";
            $ContactData->Comment = !empty($data['Comment']) ? $data['Comment'] : "";
			            
            
            //save the data
             $EmailData = $ContactData;
             $ContactData->write();
       
            $this->SendNotificationEmail($ContactData);
            $this->SendThankYouEmail($ContactData);
            
        $this->redirect('thank-you');
        }
    
public function SendThankYouEmail($data){
	 global $emailConfig;
           $site_config = SiteConfig::current_site_config(); 
	    $subject = "Thank You for Contacting " . $site_config->Title;
        $message = "";
        $email = new Email();
	//$email->setTo($data['Email']);
       // $email->setTo('kmulrich@yahoo.com');
                $email->setTo($data->Email,$data->FirstName . ' ' . $data->LastName );
		$email->setFrom($emailConfig['From'],$emailConfig['FromName']);
		$email->setReplyTo($emailConfig['From'],$emailConfig['FromName']);
		//$email->addCustomHeader('From',$emailConfig['FromName']);
		$email->setSubject($subject);
		$email->setHTMLTemplate('Emails\\ContactThankYou');
                //$email->setData($data);
		//$email->populateTemplate(new ArrayData(array('Data'=>$EmailData)));
//			$email->addCustomHeader();
     //     print_r($email); 
	 $deployed = $email->send();
	return $deployed;
}

public function SendNotificationEmail($data){
	 global $emailConfig;
        $site_config = SiteConfig::current_site_config(); 
	$subject =  $site_config->Title . " Contact Submission";
        $message = "";
        $email = new Email();
	//$email->setTo($data['Email']);
       // $email->setTo('kmulrich@yahoo.com');
      //  Debug::show($emailConfig['NotificationEmail']);
                $email->setTo($emailConfig['NotificationEmail'], 'RSC');
		$email->setFrom($emailConfig['From'],$emailConfig['FromName']);
		$email->setReplyTo($emailConfig['From'],$emailConfig['FromName']);
		//$email->addCustomHeader('From',$emailConfig['FromName']);
		$email->setSubject($subject);
		$email->setHTMLTemplate('Emails\\ContactSubmission');
                $email->setData($data);
		//$email->populateTemplate(new ArrayData(array('Data'=>$data)));
//			$email->addCustomHeader();
     //     print_r($email); 
	 $deployed = $email->send();
	return $deployed;
}

}
