<?php

namespace app\controllers;

use yii;
use yii\rest\Controller;
use app\models\Mailbox;
//use yii\base\Exception;

class RestController extends Controller
{

    CONST WELCOME = [ "MedApi" => "v.1.3", "result"=>null ];
    CONST ERROR = [  "message" => null  ];
    CONST AUTH_KEY = "69F651-C95E8E44-2832B6-2DBF40";
    CONST DOMAIN = ["goldendent.hu","goldendental.hu","goldenmedical.hu"];

    public $layout = 'rest_layout';

    private $_welcome;
    private $_error;
    private $_header;

    public function __construct($id, $module)
    {
        parent::__construct($id,$module);
    }

    public function beforeAction($action)
    {

        $this->_error = self::ERROR;

        $this->_welcome = self::WELCOME;
        $this->_welcome['hash'] = hash("SHA256",self::AUTH_KEY);
        $this->_welcome['timestamp'] = date("Y-m-d H:i:s",time());

        $this->_header['auth'] = @$_SERVER['HTTP_AUTH'];

        if(empty($this->_header['auth'])){
            $this->_welcome['result'] = "error";
            $this->_error['message'] = "Auth key missing";
        }elseif( $this->_header['auth'] != $this->_welcome['hash'] ){
            $this->_welcome['result'] = "error";
            $this->_error['message'] = "Auth key mismatch";
        }

        if( !empty($this->_error['message']) ){
            $this->action->actionMethod = 'actionError';
            $this->action->id = 'error';
        }
        else
        {
             $this->_welcome['result'] = "success";
        }

        return true;
    }


    /**
     * Displays welcome
     *
     * @return string
     */
    public function actionIndex()
    {

        //echo "<pre>";print_r(Yii::$app->db);echo "</pre>";exit;
        //echo "<pre>";print_r($_GET);print_r($_POST);print_r($_SERVER);echo "</pre>";exit;

        if(!empty($_POST)){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "POST not allowed",
            ]); 
        }

        // if(empty($_GET)){
        //     return $this->runAction('error',[
        //         "result"  => "error",
        //         "message" => "missing parameter",
        //     ]); 
        // }

        //print json_encode( $this->_welcome );exit;
        return $this->render('index',[ "data"  => json_encode($this->_welcome) ]);
    }


    public function actionFind_mailbox()
    {
    
        if(($id = @$_GET['id']) == false){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "missing or wrong mailbox parameter",
            ]);    
        }

        if(($domain = @$_GET['domain']) == false){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "missing domain parameter",
            ]);    
        }
        
        if( !in_array($domain, SELF::DOMAIN) ){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "wrong domain parameter",
            ]); 
        }

        $mailboxName = $id."@".$domain;

        $mbox = Mailbox::findOne($mailboxName);
        //print_r($mbox->toArray());exit;

        if( empty($mbox) )
        {
           
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "no result",
            ]); 
        }

        return $this->render('index',[ 
                "data" => json_encode($mbox->toArray()), 
                "pwd" => [
                    "bnirK5CD"=> crypt('bnirK5CD','$1$68934485$') ,
                    "L24MlHhV"=> crypt('L24MlHhV','$1$68999e4e$') 
                ]
            ]
        );
    }

    public function actionCreate_mailbox(){ 


        if((    $username = @$_REQUEST['username']) == false 
            || ($pwd = @$_REQUEST['pwd']) == false
            || ($domain = @$_REQUEST['domain']) == false
        )
        {
            
            if(empty($_REQUEST)){
                $errMsg = "call type mismatch";
            }else{               
                $errMsg = "missing parameter(s)";
            }                 

            return $this->runAction('error',[
                "result"  => "error",
                "message" => $errMsg,
            ]);    
            
        }

        if( !in_array($domain, SELF::DOMAIN) ){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "wrong domain parameter",
            ]); 
        }

        $name = @$_GET['name'];

        //$quota = @$_GET['quota'];
        //print_r($_GET);print $username;
        //print crypt('PASSWORDSTRING','$1$68934485$');
        //exit;

        $full_email_name = $username."@".$domain;

        $checkMbox = Mailbox::findOne( $full_email_name );
        
        if(empty($checkMbox)){
        
            $mbox = new Mailbox;
            $mbox->name = $name ? : "";
            $mbox->local_part = $username;
            $mbox->username = $full_email_name;
            $mbox->maildir = $full_email_name."/";
            $mbox->domain = $domain;
            $mbox->created = date("Y-m-d H:i:s",time());
            $mbox->active = 1;
            $mbox->password = $pwd;
            $mbox->password_expiry = date("Y-m-d H:i:s",time()+365*2*1000);
            //$mbox->quota = $quota;

            try{
                $mbox->save();

                $this->_welcome['data'] = [
                    "username"  => $full_email_name,
                    "db_result"    => "success",
                ];

            }
            catch( \yii\db\Exception $e )
            {
                 $this->_welcome['data'] = [
                    "username"   => $full_email_name,
                    "db_result"  => "error",
                    "db_message" => $e->errorInfo,
                ];
                
            }

            //if( $this->_welcome['data']['db_result'] == 'success' ){
                
                //$res = shell_exec("maildirmake /var/mail/virtual/{$mbox->maildir}");
                //print_r($res);exit;
                
            //}else{
                
            //}

        }
        else
        {
             $this->_welcome['data'] = [
                "username"   => $full_email_name,
                "db_result"  => "error",
                "db_message" => "Mailbox already created!",
            ];
        }

        return $this->render('create_mailbox',[ "data" => json_encode($this->_welcome),  ]);
    }

    public function actionShow_mailboxes(){

        if(($domain = @$_GET['domain']) == false){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "missing domain parameter",
            ]);    
        }
        
        if( !in_array($domain, SELF::DOMAIN) ){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "wrong domain parameter",
            ]); 
        }

        $mbox = Mailbox::findAll(["domain" => $domain ]);
            //print_r($mbox->toArray());exit;

            return $this->render('show_mailboxes',[
                "data" => $mbox, 
            ]);
        
    }

    public function actionError($result=null,$message=null)
    {
        if( !empty($result)) $this->_welcome['result'] = $result;
        if( !empty($message)) $this->_error['message'] = $message;
        //print_r($this);

        return $this->render('error',[
            "data" =>   array_merge($this->_welcome , $this->_error) ,
        ]);
    }
    
}

?>
