<?php

class Customer_contact extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->load->model('Security', 'security_model');
        $this->load->model("Customer_contact_Model");
        $this->security_model->admin($this->session->userdata('session_id'), $this->session->userdata('user_id'), $this->session->userdata('username'));
    }


    function index()
    {
        $data['_inactive_loading'] = true;
        $data['record'] = json_decode(json_encode($this->Customer_contact_Model->get()), true);
        $data['_view'] = 'customer_contact';
        $this->load->view('backend/index', $data);
    }

    public function listing()
    {
        $request = $this->input->get();

        $data = $this->Customer_contact_Model->listing($request);
        echo json_encode($this->Customer_contact_Model->build_datatables($request['draw'], $this->Customer_contact_Model->totalCount(), $this->Customer_contact_Model->filteredCount($request), $data), JSON_UNESCAPED_UNICODE);
    }

    public function reply()
    {

        $get = $this->input->get();
        $data['_inactive_loading'] = true;
        $data["_view"] = 'reply';
        $data['csrf'] = array(
            'name' => $this->security->get_csrf_token_name(),
            'hash' => $this->security->get_csrf_hash()
        );
        $data['id'] = $get['id'];
        $this->load->view('backend/index', $data);
    }

    public function replied()
    {
        $post = $this->input->post();
        $this->load->model("Customer_contact_Model");
        $id = $post['id'];
        $customer_information = json_decode(json_encode($this->Customer_contact_Model->get_id($id)),true);
	
		
        $data = [
            'title' => $post['title'],
            'content' => $post['content'],
			'address' => $customer_information[0]['email']
        ];
        $this->_emailAction($data);
      
        $this->Customer_contact_Model->replied($id);
        $data['_inactive_loading'] = true;
        $data["_view"] = 'customer_contact';

        $this->load->view('backend/index', $data);
    }

    private function _emailAction($data)
    {
        //require dirname(__DIR__) . "/libraries/sendgrid/sendgrid-php.php";
        //require_once dirname(__DIR__) . '/libraries/Document.php';
        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 = strip_tags($data['title']);
        $c = $doc->getElementById('content');
        $c->nodeValue = '';
        $c->nodeValue = strip_tags($data['content']);
       // $c->appendChild($doc->createElement('p', $data['content']));
        /*
        $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', "---------------"));
        */
        //$this->load->model('Questions_Model', 'questions_model');
        //$questionslist = $this->questions_model->get($data);
        // if ($product_code) {
        //     $this->append_product_code($product_code);
        // }

        // if (is_array($chosen_prod)) {
        //     foreach ($chosen_prod as $code) {
        //         $this->append_product_code($code);
        //     }
        // }

        // $d = $data['content'];
        //print improve problem
        //$c->appendChild($doc->createElement('p', "你想改善問題:"));

        /* foreach ($questionslist as $questionrow) {
            if ($questionrow->type_id == 1) {
                if (in_array($questionrow->id, $data['questionanswer'])) {
                    $c->appendChild($doc->createElement('p', $questionrow->question));
                }
            }
        }*/

        //end print improve problem
        /* $c->appendChild($doc->createElement('p', "---------------"));
        //print info list
        $c->appendChild($doc->createElement('p', "專業項目諮詢:"));

        foreach ($questionslist as $questionrow) {
            if ($questionrow->type_id == 2) {
                if (in_array($questionrow->id, $data['questionanswer'])) {
                    $c->appendChild($doc->createElement('p', $questionrow->question));
                }
            }
        }*/
        //end print info list

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

        // $subj = $data['subj'];
        $subj = "客戶查詢";

        $email->setFrom("contact_form@at-webs.hk", "Kitty_skin");
        $email->setSubject($subj);
        // $email->addTo("bear@at-creative.com", "Bear");
        //$email->addTo('info@kinfu.com.hk', "info");
        //$email->addTo('edward@at-creative.com');
        $email->addTo($data['address']);
        // $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;
        }
    }
}
