<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Contactus extends CI_Controller {

    public $layout = 'full';
    public $module = 'contactus_view';
    public $model = 'Projects_model';

    public function __construct() {
        parent::__construct();
        // $this->load->model($this->model);
        // $this->_primary_key = $this->{$this->model}->_primary_keys[0];
        $this->load->model('Settings_Model','settings_model'); 
    }

    public function index() {

        $data=array();
        // $data['sliders'] = $this->db->get('sliders')->result();
        // $data['categories'] = $this->db->get('categories')->result();
        // $data['testimonials'] = $this->db->get('testimonials')->result();
        // $data['partners'] = $this->db->limit(6)->get('partners')->result();
        // $this->{$this->model}->order_by['project_id'] = 'DESC';
        // $this->{$this->model}->limit = 6;
        // $data['items'] = $this->{$this->model}->get();

        //load setting value
        $data['settings']= new stdClass;
        foreach ($this->settings_model->get() as $setting) {
            // echo "get setting";
            $data['settings']->{ $setting->key } = $setting->value;
            
        }
        //end load setting value

        //load main menu
        $this->load->model('Landingmain_Model','landingmain_model'); 
        $data['landingmain'] = $this->landingmain_model->get();    
        //end load main menu

        //load sub menu
        $this->load->model('Landingsubmenu_Model','landingsubmenu_model');
        $data['landingsubmenu'] = $this->landingsubmenu_model->get();
        //end load submenu


        //load content menu
        $this->load->model('Landingcontentmultistyle_Model','landingcontentmultistyle_model');
        $data['landingcontentmultistylemenu'] = $this->landingcontentmultistyle_model->get();
        //end　load content menu　

        
        //get questions content
        $this->load->model('Questions_Model','questions_model');
        $data['questionscontent'] = $this->questions_model->get();
        //end get question content

        
       //echo    $displaypage;

        // var_dump($data['landingcontent']);   
        //end loading page content

        $this->load->view($this->module, $data);
    }

   public function formsubmit() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('inputname', 'Name', 'trim|required');
        $this->form_validation->set_rules('inputemail', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('staticmobile', 'Phone', 'trim|required');

        if(!empty($this->input->post('recaptcha_response'))){
           if($this->googlecaptchaverify($this->input->post('recaptcha_response'))==true){
            // echo "google verified = true";

                // $this->form_validation->set_rules('inputgender', 'Gender', '');
                $data['success'] = false;

                $inputname="";
                if($this->input->post('inputname',TRUE) != false){
                         $inputname=$this->input->post('inputname',TRUE);
                }
                $inputemail="";
                if($this->input->post('inputemail',TRUE) != false){
                         $inputemail=$this->input->post('inputemail',TRUE);
                }
                $staticmobile="";
                if($this->input->post('staticmobile',TRUE) != false){
                         $staticmobile=$this->input->post('staticmobile',TRUE);
                }
                $inputgender="";
                if($this->input->post('inputgender',TRUE) != false){
                         $inputgender=$this->input->post('inputgender',TRUE);
                }
                $inputage="";
                if($this->input->post('inputage',TRUE) != false){
                         $inputage=$this->input->post('inputage',TRUE);
                }
                $inputmessage="";
                if($this->input->post('inputmessage',TRUE) != false){
                         $inputmessage=$this->input->post('inputmessage',TRUE);
                }


                // echo "inputage";
                // echo $inputage;

                if ($this->form_validation->run() == TRUE) {
                    $data= array(
                        'inputname'=>$inputname,
                        'inputemail'=>$inputemail,
                        'staticmobile'=>$staticmobile,
                        'inputgender'=>$inputgender,
                        'inputage'=>$inputage,
                        'inputmessage'=>$inputmessage,
                    );
                    // var_dump($data);
                    $this->load->model('Contactus_Model','contactus_model');
                    $result=$this->contactus_model->insertForm($data);
                    if($result==true){
                        // echo "insert success";
                    }
                    // @mail(config('webmaster_email'), 'Message from MaroCms', ""
                    //                 . "Full Name: $_POST[name]\n"
                    //                 . "Email: $_POST[email]\n"
                    //                 . "Phone: $_POST[phone]\n"
                    //                 . "Message: $_POST[message]\n"
                    //                 . "");
                    
                    $emailresult=$this->_emailAction($data);
                    if($emailresult==true){
                        // echo "succeful send email"
                    }
                    $data['success'] = true;
                }
                $data['title']="";
                //load setting value
                $data['settings']= new stdClass;
                foreach ($this->settings_model->get() as $setting) {
                    // echo "get setting";
                    $data['settings']->{ $setting->key } = $setting->value;
                    
                }
        //end load setting value
        }//if($this->googlecaptchaverify($this->input->post('recaptcha_response'))==true){
           else{
            // echo "google verified = false";
           }
           // echo "recaptcha_response";     
           // echo $this->input->post('recaptcha_response');     
        }//if(isset($this->input->post('recaptcha_response')){

        $this->load->view('contactussubmit_view', $data);
    }
    private function findpage($page){
    	$this->load->model('Landingcontentmultistyle_Model','landingcontentmultistyle_Model'); 
        $id = $this->landingcontentmultistyle_Model->findpage($page);   
        return $id;
    }
    private function verifyaccount(){

    }
    private function _emailAction($data) {
        require(dirname(__DIR__) . "/libraries/sendgrid/sendgrid-php.php");
        require_once dirname(__DIR__) . '/libraries/Document.php';

        global $p, $doc, $a, $c;
        $email = new \SendGrid\Mail\Mail();
        
        // $chosen_prod = isset($data['chosen_prod']) ? $data['chosen_prod'] : false;
        // $product_code = isset($data['product_code']) ? $data['product_code'] : false;

        $doc = new Document();
        $doc->loadHTMLFile('application/libraries/email.html');
        $doc->getElementsByTagName('title')->item(0)->nodeValue = 'Contact';
        $doc->getElementById('greeting')->nodeValue ='';
        $c = $doc->getElementById('content');
        $c->nodeValue = '';

        $c->appendChild($doc->createElement('p', "姓名:".$data['inputname']));
        $c->appendChild($doc->createElement('p', "電郵:".$data['inputemail']));
        $c->appendChild($doc->createElement('p', "電話:".$data['staticmobile']));
        $c->appendChild($doc->createElement('p', "性別:".$data['inputgender']));

        $displayage="";
        if($data['inputage']==1){
            $displayage="18-25";
        }
        if($data['inputage']==2){
            $displayage="25-35";
        }
        if($data['inputage']==3){
            $displayage="35-45";
        }
        if($data['inputage']==4){
            $displayage="45-60";
        }
        if($data['inputage']==5){
            $displayage="60+";
        }
        $c->appendChild($doc->createElement('p', "年齡:".$displayage));
        $c->appendChild($doc->createElement('p', "內容:".$data['inputmessage']));



        $html = $doc->saveHTML();
//        echo($html);die;

        // $subj = $data['subj'];
        $subj = "客戶聯絡";
        
        $email->setFrom("contact_form@at-webs.hk", "Amigo Rejuvence");
        $email->setSubject($subj);
        // $email->addTo("bear@at-creative.com", "Bear");
        //$email->addTo('info@kinfu.com.hk', "info");
        $email->addTo('jack@at-creative.com');
        // $email->addBcc('jack@at-creative.com');
        // $email->addBcc('arvid@at-creative.com');
        // $email->addBcc('daniel@at-creative.com');
       

        $email->addContent(
                "text/html", $html
        );
        // $email->addContent(
        //         "text/html", "abc"
        // );

        //end sample email message
        $sendgrid = new \SendGrid('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');
        try {
            $response = $sendgrid->send($email);
            //var_dump($response);
            //echo 'Done!';
            return true;
            // print $response->statusCode() . "\n";
            // print_r($response->headers());
            // print $response->body() . "\n";
        } catch (Exception $e) {
            //echo 'Caught exception: ' . $e->getMessage() . "\n";
            return false;
        }
    }

    private function googlecaptchaverify($recaptcha_response){
        // Build POST request:
        $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
        $recaptcha_secret = '6Lcnyu0ZAAAAANgwhF9HI2hQ5Tuf-GvmnSBR1fo6';
        // $recaptcha_response = $_POST['recaptcha_response'];
        // $recaptcha_response = $recaptcha_response;

        // Make and decode POST request:
        $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
        $recaptcha = json_decode($recaptcha);

        // Take action based on the score returned:
        if ($recaptcha->score >= 0.5) {
            // Verified - send email
            return true;
        } else {
            // Not verified - show form error
            return false;
        }
    }
}

?>