<?php

namespace Controller;

class Email {

    public $c = [];
    public $data = [];
    public $path = "";
    
    function __construct() {

    }

    function load_form_config($token) {
        $f3 = \Base::instance();
        
        $token_db = $f3->get('TEMP') . "CEform/";
        $db = new \DB\Jig($token_db,\DB\Jig::FORMAT_JSON);
        $formcall = new \DB\Jig\Mapper($db,'form_calls');

        if($formcall->load(['@token = ?', $token])) {
            $f3->config($formcall->form);
            $f3->set('form_path', $formcall->path);
            $this->path = $formcall->path;
            return true;
        } else {
            return false;
        }
    }
    
    function get_post_data() {
        $f3 = \Base::instance();
        
        $token = $f3->get('POST.xss-token');
        if (ctype_alnum( $token )) {
            if ($this->load_form_config($token)) {

                foreach ($f3->get('fields') as $field => $def) {
                    $this->data['fields'][$field] = $f3->get('POST.'.$field);
                }
                $this->data['private'] = $f3->get('private');
                
                return true;
            } else {
                return false;
            }
        } else {
            // wrong xss-token supplied - malicous attac expected
            die;
        }
    }
    
    function send() {
        $f3 = \Base::instance();
        
        $this->get_post_data();

        $to = $this->data['private']['email'];
        $subject = $this->data['private']['subject'];
        $message = $this->data['fields']['message'];

        $c = $this->data['private']['emailconfig'];
        
        $template = substr($this->path,strlen($f3->get('CONTENT_BASE'))+2) . $this->data['private']['template'];
        
        
        $f3->set('fields', $this->data['fields']);

        
        $headers = [
            "MIME-Version"=>"1.0",
            "Content-type"=>"text/html",
            "From" => $c['from']
        ];
        //$c = $this->c;
        $smtp = new \SMTP(
            $c['host'],
            $c['port'],
            $c['scheme'],
            $c['user'],
            $c['pass'],
        );
        
        $smtp->set('To', $to);
        $smtp->set('Subject',$subject);
        foreach ($headers as $k=>$v) {
            $smtp->set($k,$v);
        }
        
        $email = \Template::instance()->render($template,'text/html');
        //echo $email;
        if ($smtp->send($email)) {
            $success = true;
        } else {
            $success = false;
        }

        if ($success) {
            $f3->reroute("/email/success?email=".urlsafe_b64encode($email)."&lang=".$f3->get('LANG'));
        } else {
            #$f3->reroute("/email/error");
            echo \Template::instance()->render($template,'text/html');
            die;
        }
    }
}