<?php


class SiteController extends Controller
{

    public $defaultAction = 'index';
    public $layout = '//layouts/main';

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // newsletter. is the prefix we are going to use on our URL
            'newsletter.' => 'shortcodes.NewsletterSubscribeWidget',
            'postComment' => array(
                'class' => 'application.components.actions.PostComment',
            ),
        );
    }

    /**
     * Manages all models.
     */
    public function actionSearch()
    {
        $criteria = new CDbCriteria;
    }

    public function actionIndex()
    {
        //$this->setData('TEST',10);
        //$this->setSeoProperty('keywords',"mmbashiti");
        // Yii::app()->session['first_visit'];
        // if(isset(Yii::app()->session['first_visit']))
        // {
        //     echo 'test yesy';
        //     // echo json_encode(array('status'=>'sucsess', 'msg'=> 'test'));

        // }else{

        $this->render('index');
        // }
    }
    public function actionJoinUs()
    {
        //$this->setData('TEST',10);
        $this->render('joinUs');
    }
    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {

        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {


            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                    "Reply-To: {$model->email}\r\n" .
                    "MIME-Version: 1.0\r\n" .
                    "Content-Type: text/plain; charset=UTF-8";

                $senderInfo = Yii::t(
                    'site',
                    "____________Sender Info____________<br/>\r\n"
                        . "Name: {name}<br/>\r\n"
                        . "E-mail: {email}<br/>\r\n"
                        . "____________Message:____________<br/><br/>\r\n",
                    array(
                        '{name}' => $model->name,
                        '{email}' => $model->email
                    )
                );



                Yii::import('application.extensions.phpmailer.JPhpMailer');
                $mail = new JPhpMailer;
                $mail->IsSMTP(); // enable SMTP
                $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
                $mail->SMTPAuth = true; // authentication enabled
                $mail->SMTPSecure = Yii::app()->options->get('SMTP-SECURE'); // secure transfer enabled REQUIRED for GMail
                $mail->Host = Yii::app()->options->get('SMTP-HOST');
                $mail->Port = Yii::app()->options->get('SMTP-PORT'); // or 587
                $mail->IsHTML(true);
                $mail->Username = Yii::app()->options->get('SMTP-USERNAME');
                $mail->Password = Yii::app()->options->get('SMTP-PASSWORD');
                $mail->SetFrom(Yii::app()->options->get('SMTP-FROM-EMAIL'), Yii::app()->options->get('SMTP-FROM-NAME'));
                $mail->SetFrom($model->email, $model->name);
                $mail->Subject = $model->name;
                $mail->AltBody = strip_tags($senderInfo . $model->body);
                $mail->MsgHTML($senderInfo . $model->body);
                $mail->AddAddress(Yii::app()->options->get('CONTACT_EMAIL', Yii::app()->params['adminEmail']), 'Administrator');
                $result = $mail->Send();

                //		@mail(Yii::app()->options->get('CONTACT_EMAIL', Yii::app()->params['adminEmail']), $subject, $senderInfo . $model->body, $headers);

                Yii::app()->user->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model,));
    }

    public function actionSitemap()
    {

        $this->render('sitemap');
    }

    public function actionMigate()
    {
        $alterFile = Yii::app()->basePath . '/../alter.sql';

        $content = '';
        if (is_file($alterFile)) {
            $content = file_get_contents($alterFile);
        }

        $result = Yii::app()->db->createCommand($content)->execute();

        echo '<xmp dir="ltr">', var_dump($result), "</xmp>";
        exit;
    }


    public function actionDirectors()
    {
        $this->render('directors');
    }

    public function actionAllNews()
    {
        $this->render('AllNews');
    }
    public function actionSearchResault()
    {
        $this->render('searchResault');
    }


    public function actionVideo($id)
    {
        $criteria = new CDbCriteria;
        //  $criteria ->video_category=$id;
        //  $criteria->compare('video_category',$this->video_category=$id);
        $criteria->order = 'id desc';

        $pages = new CPagination(Video::model()->count());

        // Set Page Limit

        $pages->pageSize = 5;

        // Apply page criteria to CDbCriteria

        $pages->applyLimit($criteria);

        $videos = Video::model()->findAllByAttributes(array('video_category' => $id), $criteria);
        $catname_ar = VideoCategory::model()->findByPk($id)->name_ar;
        $catname_en = VideoCategory::model()->findByPk($id)->name_en;

        if (!empty($videos)) {
            $this->render('videos', array('videos' => $videos, 'pages' => $pages, 'catname_ar' => $catname_ar, 'catname_en' => $catname_en));
        } else {
            $this->render('video_category');
        }
    }


    public function actionContactUs()
    {
        $this->render('contactUs');
    }

    public function actionAccounts()
    {
        $param = "";
        if (isset($_GET['type']))
            $param = $_GET['type'];
        //set seo
        $model = Article::model()->findByAttributes(array('slug' => $param));
        if ($model != null) {
            $this->setSeoProperty('keywords', $model->meta);
            if (isset($model->image) && $model->image != "" && $model->image != null)
                $this->setSeoProperty('image_src', Yii::app()->getBaseUrl(true) . "/uploads/Article/" . $model->image);
            $this->setSeoProperty('title', $model->title);
            $lang = Yii::app()->getLanguage();
            if ($lang == 'en') {
                $this->setSeoProperty('description', strip_tags($model->description_en));
            } else {
                $this->setSeoProperty('description', strip_tags($model->description_ar));
            }
        } else {
            $this->setSeoProperty('keywords', 'accounts');
            $this->setSeoProperty('title', 'accounts');
            $this->setSeoProperty('description', "Albaraka Accounts");
        }
        //end of seo

        $this->render('acounts', array('type' => $param));
    }

    public function actionAboutBank()
    {
        $this->render('aboutBank');
    }

    public function actionQuestionnaireAll()
    {
        $this->render('questionnaireAll');
    }

    public function actionQuestionnaire($id)
    {
        //set seo

        $this->setSeoProperty('keywords', 'Questionnaire استبيانات');
        $this->setSeoProperty('title', 'Questionnaire');
        $this->setSeoProperty('description', "Albaraka Bank Syria Questionnaire");

        //end of seo
        $questionnaires = Questionnaire::model()->findByPK(array('id' => $id));

        // if(count($_POST)){
        //     echo '<pre>' . var_export($_POST, true) . '</pre>';
        //     die;
        // }

        if (isset($_POST['verifyCode'])) {
            $ca = Yii::app()->getController()->createAction('captcha');
            if (!$ca->validate($_POST['verifyCode'], false)) // false stands for 'case insensitive'
            {
                // var_dump("Wrong Capatcha");

                Yii::app()->setLanguage(isset(Yii::app()->session['lang']) ? Yii::app()->session['lang'] : 'ar');
                $lang = Yii::app()->getLanguage();
                if ($lang == 'en') {
                    echo json_encode(array('status' => 'error', 'msg' => ' wrong captcha '));
                } else {
                    echo json_encode(array('status' => 'error', 'msg' => 'رمز التحقق خاطئ'));
                }
                die;

                //    Yii::app()->user->setFlash('alert-danger','Wrong CAPTCHA.');
                //     $this->render('questionnaire',array('questionnaires'=>$questionnaires));
                //     return;
            }
        }

        $rand = uniqid();

        if (isset($_POST['Range'])) {
            $questions = $_POST['Range'];
            foreach ($questions as $key => $question) {
                $model = new QuestionnaireAnswer;
                $model->question_id = explode("-", $key)[0];
                $model->uniq_id = $rand;

                if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                    $model->ip_address = $_SERVER['HTTP_CLIENT_IP'];
                } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $model->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
                } else {
                    $model->ip_address = $_SERVER['REMOTE_ADDR'];
                }

                $model->data = $question;
                $model->create_datetime = date("yy-mm-dd H:i:s");
                $model->save();
            }
        }

        if (isset($_POST['Text']) || isset($_POST['CheckBox']) || isset($_POST['Radio'])) {
            // $rand = uniqid();

            //get all text 
            if (isset($_POST['Text'])) {
                $questions = $_POST['Text'];
                foreach ($questions as  $key => $question) {
                    $model = new QuestionnaireAnswer;
                    //echo 'question id = ';
                    $model->question_id = $key;
                    $model->uniq_id = $rand;

                    // $model->ip_address=$_SERVER['REMOTE_ADDR'];
                    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                        $model->ip_address = $_SERVER['HTTP_CLIENT_IP'];
                    }
                    //whether ip is from proxy
                    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                        $model->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
                    }
                    //whether ip is from remote address
                    else {
                        $model->ip_address = $_SERVER['REMOTE_ADDR'];
                    }

                    //$data=$question;
                    $model->data = $question; //implode(',', $data);
                    $model->create_datetime = date("yy-mm-dd H:i:s");
                    $model->save();
                }
            }

            if (isset($_POST['Radio'])) {
                $questions = $_POST['Radio'];
                foreach ($questions as  $key => $question) {
                    $model = new QuestionnaireAnswer;
                    //echo 'question id = ';
                    $model->question_id = $key;
                    $model->uniq_id = $rand;

                    // $model->ip_address=$_SERVER['REMOTE_ADDR'];
                    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                        $model->ip_address = $_SERVER['HTTP_CLIENT_IP'];
                    }
                    //whether ip is from proxy
                    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                        $model->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
                    }
                    //whether ip is from remote address
                    else {
                        $model->ip_address = $_SERVER['REMOTE_ADDR'];
                    }

                    //$data=$question;
                    $model->data = $question; //implode(',', $data);
                    $model->create_datetime = date("yy-mm-dd H:i:s");
                    $model->save();
                }
            }
            if (isset($_POST['CheckBox'])) {
                $questions = $_POST['CheckBox'];
                foreach ($questions as  $key => $question) {
                    $model = new QuestionnaireAnswer;
                    //echo 'question id = ';
                    $model->question_id =  explode("-", $key)[0];
                    $model->uniq_id = $rand;

                    // $model->ip_address=$_SERVER['REMOTE_ADDR'];
                    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                        $model->ip_address = $_SERVER['HTTP_CLIENT_IP'];
                    }
                    //whether ip is from proxy
                    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                        $model->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
                    }
                    //whether ip is from remote address
                    else {
                        $model->ip_address = $_SERVER['REMOTE_ADDR'];
                    }

                    // $data=$question;
                    $model->data = $question;
                    $model->create_datetime = date("yy-mm-dd H:i:s");
                    if (!$model->save());
                    // var_dump($model->getErrors());
                }
            }
            // $msg="شكراً لوقتك,";
            // if(isset(Yii::app()->session['lang'])&&  Yii::app()->session['lang']!="ar")
            // {
            // 	$msg="Thanks for your time";
            // }
            Yii::app()->setLanguage(isset(Yii::app()->session['lang']) ? Yii::app()->session['lang'] : 'ar');
            $lang = Yii::app()->getLanguage();
            if ($lang == 'en') {
                echo json_encode(array('status' => 'sucsess', 'msg' => 'Thanks for your time and attention '));
            } else {
                $next_questionnaires = Questionnaire::model()->findByAttributes(array('featured' => '2'));
                echo json_encode(array(
                    'status' => 'sucsess',
                    'msg' => 'شكراً لوقتك واهتمامك ' . ($next_questionnaires != Null ? '<br> هناك استبيان اخر:  <a href="' . Yii::app()->request->baseUrl . '/site/questionnaire/' . $next_questionnaires->id . '" >' . $next_questionnaires->title . '</a>' : '') . ''
                ));
            }
            die;

            //	
            // $this->render('questionnaireAll',array('message'=>$msg));
            // return;
        }

        // echo '<pre>' . var_export($questionnaires->questionnaireQuestions, true) . '</pre>';
        // die;
        $this->render('questionnaire', array('questionnaires' => $questionnaires));
    }

    public function actionNews()
    {
        $this->render('news');
    }

    public function actionFinancialStatements()
    {
        //set seo
        $model = null; //Article::model()->findByAttributes(array('slug'=>$param));
        if ($model != null) {
            $this->setSeoProperty('keywords', $model->meta);
            if (isset($model->image) && $model->image != "" && $model->image != null)
                $this->setSeoProperty('image_src', Yii::app()->getBaseUrl(true) . "/uploads/Article/" . $model->image);
            $this->setSeoProperty('title', $model->title);
            $lang = Yii::app()->getLanguage();
            if ($lang == 'en') {
                $this->setSeoProperty('description', strip_tags($model->description_en));
            } else {
                $this->setSeoProperty('description', strip_tags($model->description_ar));
            }
        } else {
            $this->setSeoProperty('keywords', 'Financial Statements بيانات مالية');
            $this->setSeoProperty('title', 'Financial Statements');
            $this->setSeoProperty('description', "Albaraka Bank Syria Financial Statements");
        }
        //end of seo

        $this->render('financialStatements');
    }

    public function actionFaq()
    {
        //set seo

        $this->setSeoProperty('keywords', 'FAQ Albaraka Bank Syria ');
        $this->setSeoProperty('title', 'FAQ');
        $this->setSeoProperty('description', "Albaraka Bank Syria FAQ");

        //end of seo
        $this->render('faq');
    }

    public function actionAnnualReports()
    {
        //set seo

        $this->setSeoProperty('keywords', 'Annual Reports Albaraka Bank Syria ');
        $this->setSeoProperty('title', 'Annual Reports');
        $this->setSeoProperty('description', "Albaraka Bank Syria Annual Reports");

        //end of seo

        $type = "";
        if (isset($_GET['type']))
            $type = $_GET['type'];
        $this->render('annualReports', array('type' => $type));
    }

    public function actionVlaid()
    {
        $this->render('vlaid');
    }
    public function actionExchangeRate()
    {
        //set seo

        $this->setSeoProperty('keywords', 'Albaraka Bank Syria Exchange Rate');
        $this->setSeoProperty('title', 'Exchange Rate');
        $this->setSeoProperty('description', "Albaraka Bank Syria Exchange Rate");

        //end of seo
        $this->render('exchangeRate');
    }

    public function actionCommission()
    {
        //set seo

        $this->setSeoProperty('keywords', 'Albaraka Bank Syria Commissions');
        $this->setSeoProperty('title', 'Commissions');
        $this->setSeoProperty('description', "Albaraka Bank SyriaCommissions");

        //end of seo
        $this->render('commission');
    }

    public function actionCalculator()
    {
        $finances = CalculatorFinance::model()->findAll();
        $currencies = CalculatorAverageProfitRate::model()->findAll();

        $temp_f = [];
        foreach ($finances as $finance) {
            $temp_f[] = [
                'finance_type' => $finance->finance_type,
                'finance_type_en' => $finance->finance_type_en,
                'max_duration_months' => $finance->max_duration_months,
                'minimum_first_payment' => $finance->minimum_first_payment,
                'profit_ratio' => $finance->profit_ratio,
                'maximum_duration_of_finance' => $finance->maximum_duration_of_finance,
                'maximum_duration_of_finance_en' => $finance->maximum_duration_of_finance_en,
            ];
        }
        // echo '<pre>' . var_export(json_encode($temp_f), true) .'</pre>';
        $temp_cur = [];
        foreach ($currencies as $currency) {
            $temp_cur[] = [
                'calculator_currency' => $currency->calculator_currency,
                'profit_month' => $currency->profit_month,
                'profit_3month' => $currency->profit_3month,
                'profit_6month' => $currency->profit_6month,
                'profit_12month' => $currency->profit_12month,
                'profit_24month' => $currency->profit_24month,
                'calculator_currency_en' => $currency->calculator_currency_en,
            ];
        }
        $this->render('calculator', [
            'encoded_finaces' => json_encode($temp_f, JSON_UNESCAPED_UNICODE),
            'encoded_currencies' => json_encode($temp_cur),
        ]);
    }

    public function actionScriptClaculator()
    {
        // $finances=CalculatorFinance::model()->findAll();
        // $currencies=CalculatorAverageProfitRate::model()->findAll();
        $this->renderPartial('script_calculator', []);
    }
    public function actionScriptAccounts($articleId)
    {
        $this->renderPartial('script_accounts', [
            'articleId' =>  $articleId
        ]);
    }
    public function actionScriptIndex()
    {
        $this->renderPartial('script_index', []);
    }
    public function actionScriptSuggestion()
    {
        $this->renderPartial('script_suggestion', []);
    }
    public function actionScriptQuestionnaire()
    {
        $this->renderPartial('script_questionnaire', []);
    }
    public function actionScriptGovernorate()
    {
        $this->renderPartial('script_governorate', []);
    }
    public function actionScriptContacts()
    {
        $this->renderPartial('script_contacts', []);
    }
    public function actionScriptMenu($id)
    {
        $this->renderPartial('/layouts/script_menu', [
            'id' => $id,
        ]);
    }
    public function actionStyleMenu($id)
    {
        $this->renderPartial('/layouts/script_menu', [
            'id' => $id
        ]);
    }
    public function actionSetLanguage($lang, $currpage) //$language
    {
        // echo 'the cuurent page url is:';
        // echo $currpage;
        // echo '<br>';
        // echo    Yii::app()->request->url;
        // echo '<br>';
        //echo die;
        // echo 'you are here';
        // echo $language;
        switch ($lang) {
            case 'en':
            case 'ar':
                $lang = $lang;
                break;
            default:
                $lang = 'ar';
        }
        $currpage = strpos($currpage, '?lang') ? (substr($currpage, 0, strpos($currpage, '?lang'))) : ($currpage);
        $purify = new CHtmlPurifier();
        $purify->options = array('HTML.Allowed' => '');
        $currpage = $purify->purify($currpage);
        Yii::app()->setLanguage($lang); //$language
        Yii::app()->session['lang'] = $lang;
        // $user = Yii::app()->user;
        // $user->language = $language;
        // $user->save();
        $this->redirect($currpage);
    }

    public function actionGet_states()
    {
        $this->render('get_states');
    }

    public function actionSuggestion()
    {
        //set seo

        $this->setSeoProperty('keywords', 'Albaraka Bank Syria Suggestions');
        $this->setSeoProperty('title', 'Suggestions');
        $this->setSeoProperty('description', "Albaraka Bank Syria Suggestions");

        //end of seo
        $model = new Suggestions;
        //$this->performSuggestionAjaxValidation($model);
        if (isset($_POST['Suggestions'])) {
            $model->attributes = $_POST['Suggestions'];
            $model->serial_id = uniqid();
            Yii::app()->setLanguage(isset(Yii::app()->session['lang']) ? Yii::app()->session['lang'] : 'ar');
            $lang = Yii::app()->getLanguage();


            if ($model->save()) {
                if ($lang == 'en') {
                    echo json_encode(array('status' => 'sucsess', 'msg' => 'Thanks for your note, it will be followed, Note NO. is <strong class="dark-red-color">' . sprintf('%06d', $model->id) . '</strong>'));
                } else {
                    echo json_encode(array('status' => 'sucsess', 'msg' => 'شكراً لملاحظتك, سيتم متابعتها, رقم الملاحظة هو  <strong class="dark-red-color">' . sprintf('%06d', $model->id) . '</strong>'));
                }
                die;
            } else
            if ($lang == 'en') {

                echo json_encode(array('status' => 'error', 'msg' => 'Verification Code is wrong'));
            } else {
                echo json_encode(array('status' => 'error', 'msg' => 'رمز التحقق خاطئ'));
            }

            die;
        }


        $this->render('suggestion', array('model' => $model));
    }

    protected function performSuggestionAjaxValidation($model)
    {

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'suggestions-form') {
            //echo bootstrap . widgets . TbActiveForm::validate($model);
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }


    public function actionSiteSearch()
    {
        //set seo

        $this->setSeoProperty('keywords', 'Albaraka Bank Syria Search');
        $this->setSeoProperty('title', 'Searcch');
        $this->setSeoProperty('description', "Albaraka Bank Syria Search");

        //end of seo
        $this->render('testsearch');
    }

    public function actionVideo_category()
    {
        $this->render('video_category');
    }
    public function actionVisionMissionValues()
    {
        $this->render('visionMissionValues');
    }

    public function actionIonictest()
    {
        header("Access-Control-Allow-Origin: *");
        $msg = 'seccussfully ionic httpClient remote server test';
        echo json_encode(array('status' => 'succes', 'msg' => $msg));
    }
}
