<?php

/**
 * $Id: IndexController.php 1254 2008-09-09 08:39:51Z lule $
 * Modul strony glownej
 *
 */
class IndexController extends MainController implements ControllerInterface {

    /**
     * Strona glowna
     *
     */
    public function IndexAction($param) {
        //Utils::ArrayDisplay($param);
        //Utils::ArrayDisplay($_POST);
      //SessionProxy::SetValue("infoSent",'true');
      
        $registrationSettings = RegistrationFormSettings::GetSettings();
        $vatMultiplier = $registrationSettings['vat_multiplier'];
        $arrayPriceVat = array();
        $arrayPricePromVat = array();

        $arrayPrice = Utils::GetArrayList('mf_parameters', 'id_mf_parameters', 'price');
        $arrayPriceProm = Utils::GetArrayList('mf_parameters', 'id_mf_parameters', 'price_prom');
        foreach ($arrayPrice as $key  => $price) {
          $priceVat = $price*$vatMultiplier;
          $arrayPriceVat[$key] = $priceVat;
        }
        foreach ($arrayPriceProm as $key  => $price) {
          $priceVat = $price*$vatMultiplier;
          $arrayPricePromVat[$key] = $priceVat;
        }
        
        
        $this->smarty->assign('arrayPriceJson', str_replace('"', '', json_encode($arrayPrice)));
        $this->smarty->assign('arrayPriceVatJson', str_replace('"', '', json_encode($arrayPriceVat)));
        $this->smarty->assign('arrayPricePromJson', str_replace('"', '', json_encode($arrayPriceProm)));
        $this->smarty->assign('arrayPricePromVatJson', json_encode($arrayPricePromVat));
        $this->smarty->assign('registrationSettings', $registrationSettings);
        $this->smarty->assign('registrationPricesJson', json_encode($registrationSettings['prices']));
        $this->smarty->assign('registrationVatMultiplier', $vatMultiplier);
        

        $type = 1;

        if (isset($_POST['send'])) {
            $type = Request::GetPost('type');
        }

        $this->addScript('jQuery/messages_pl.js');
        $this->addScript('validate/validate.sendCalc.js');
        $this->addScript('validate/extras.sendCalc.js');
        $obj = MfArticleBoxDAL::GetById(1);
        $this->smarty->assign('showNews', false);
        $this->smarty->assign('indexNews', $obj);


        
        $dalData = MfParametersDAL::GetDalDataObj();
        $dalData->addCondition('type', $type);
        $dalData->addCondition('publication', 1);
        $dalData->setSortBy('sort');

        $arrayObjParameters = MfParametersDAL::GetResult($dalData);
        
        if (SessionProxy::GetValue('infoSent')) {
            SessionProxy::ClearValue('infoSent');
            $textPrice = SessionProxy::GetValue("textPrice");
            $arrayTextPrice = SessionProxy::GetValue("arrayTextPrice");
            $formData = SessionProxy::GetValue("formData");
            $idObj = SessionProxy::GetValue("qlfon");
            $objParticipant = MfParticipantDAL::GetById($idObj);
            $arrayFee = $objParticipant->getFeeFullUnserialize();

            
            //added 1,2 od 3-days
            if (in_array($arrayFee[0], ['5', '6', '7'])) {
                unset($arrayFee['disc']);
            }
            
            
            //Utils::ArrayDisplay($arrayTextPrice);
            $this->smarty->assign('arrayObjParameters', $arrayObjParameters);
            $this->smarty->assign('discPrice', $arrayFee['disc']);
            $this->smarty->assign('arrayFee', $arrayFee);
            $this->smarty->assign('objParticipant', $objParticipant);
            $this->smarty->assign('formData', $formData);
            $this->smarty->assign('textPrice', $textPrice);
            $this->smarty->assign('arrayTextPrice', $arrayTextPrice);

            $days = SessionProxy::GetValue("days");
            $this->smarty->assign('days', $days);

            $this->partialTemplate = 'IndexSent.tpl';
        }


        
        //Utils::ArrayDisplay($arrayObjParameters);
        
        if (isset($_POST['send'])) {
            //$this->SetAjaxRender();
            $this->smarty->assign('error', '');
            //			$this->smarty->assign('wrongPhone', '');
            $this->smarty->assign('wrongEmail', '');
            $this->smarty->assign('success', '');


            //===Kalkuator===============================================		
            $data = Request::GetAllPost();

            //Utils::ArrayDisplay($data);
            $validator = new Validator($data);
            $errorList = '';
            $error = '';
            $empty = '';
            $wrongEmail = '';
            $wrongPhone = '';

            //$validator->IsEmpty('name', Dictionary::Translate('required_name'));
            $validator->IsEmpty('name', Dictionary::Translate('required_field'));
            $validator->IsEmpty('surname', Dictionary::Translate('required_field'));
            $validator->IsEmpty('address', Dictionary::Translate('required_field'));
            $validator->IsEmpty('post_code', Dictionary::Translate('required_field'));
            $validator->IsEmpty('email', Dictionary::Translate('required_email'));
            $validator->IsEmailAddress('email', Dictionary::Translate('invalid_email'));
            $validator->IsEmpty('agree1', Dictionary::Translate('required_field'));
            //$validator->IsEmpty('message', Dictionary::Translate('required_message'));
            $validator->IsEmpty('g-recaptcha-response', Dictionary::Translate('required_field'));
            //Priv key: 6LfUVuoUAAAAAMurSPkwCrRja_6j5E4shtAFCzmz
            //public html key: 6LfUVuoUAAAAAD7noZ6S0rf8ZPiZKQ2KVpNBA274

            $out = $validator->GetErrorList();

            if (!empty($out)) {
                $errorList = true;
            }

            //Utils::ArrayDisplay($out);


            if ($errorList) {
                $this->smarty->assign('errorList', $validator->GetErrorList());
            } elseif ($wrongEmail) {
                
            } else {

                // Dodawanie do bazy 

                $objParticipant = MfParticipantDAL::GetEmptyObj();
                $objParticipant->setName(Request::GetPost('name'));
                $objParticipant->setSurname(Request::GetPost('surname'));
                $objParticipant->setDegree(Request::GetPost('degree'));
                $objParticipant->setPosition(Request::GetPost('position'));
                $objParticipant->setPhone(Request::GetPost('phone'));
                $objParticipant->setFax(Request::GetPost('fax'));
                $objParticipant->setEmail(Request::GetPost('email'));
                $objParticipant->setInstitution(Request::GetPost('institution'));
                $objParticipant->setAddress(Request::GetPost('address'));
                $objParticipant->setPostCode(Request::GetPost('post_code'));
                $objParticipant->setCity(Request::GetPost('city'));
                $objParticipant->setNip(Request::GetPost('nip'));
                $objParticipant->setAdditionalInfo(Request::GetPost('additional_info'));
                $objParticipant->setReferat(Request::GetPost('referat'));
                $objParticipant->setPoster(Request::GetPost('poster'));
                $objParticipant->setMessage(Request::GetPost('message'));
                $objParticipant->setMessageLong(Request::GetPost('message_long'));
                $objParticipant->setAutor(Request::GetPost('autor'));
                $objParticipant->setAgree1(Request::GetPost('agree1') ? 1 : 0);
                $objParticipant->setAgree2(Request::GetPost('agree2') ? 1 : 0);
                $objParticipant->setStatus(1);
                $objParticipant->setLocation(1);
                $objParticipant->setConferenceFee(Request::GetPost('conference_fee'));
                $participationOption = Request::GetPost('participation_option');
                if (!$participationOption) {
                    switch (Request::GetPost('conference_fee')) {
                        case '1':
                            $participationOption = 'full';
                            break;
                        case '5':
                            $participationOption = Request::GetPost('one_day_lodging') ? 'one_day_lodging' : 'one_day_no_lodging';
                            break;
                    }
                }
                $participationDays = Request::GetPost('participation_days');
                if (!$participationDays) {
                    $participationDays = Request::GetPost('days');
                }
                if (!$participationDays) {
                    $participationDays = Request::GetPost('day_conference');
                }
                $objParticipant->setParticipationOption($participationOption);
                $objParticipant->setParticipationDays($participationDays);
                $objParticipant->setOneDayLodging(Request::GetPost('one_day_lodging') ? 1 : 0);
                $objParticipant->setDiet(Request::GetPost('diet') ? Request::GetPost('diet') : 1);
                $objParticipant->setDietSpecial(Request::GetPost('diet_special'));
                $feeRoom1 = Request::GetPost('fee_room1');
                $feeRoomAddPerson = Request::GetPost('fee_room_add_person');
                $feeAngConference = Request::GetPost('fee_ang_conference');
                $objParticipant->setFeeRoom1($feeRoom1 ? 1 : 0);
                $objParticipant->setFeeRoomAddPerson($feeRoomAddPerson ? 1 : 0);
                    
                $arrayFee = array_filter([
                    Request::GetPost('conference_fee'),
                    $feeRoom1,
                    $feeRoomAddPerson,
                    $feeAngConference,
                    'disc' => Request::GetPost('conference_fee_disc')
                ]);

                if (Request::GetPost('conference_fee') == 5) {
                    $objParticipant->setFeeOneDay($participationDays);
                }

                //Utils::ArrayDisplay($arrayObjParameters);
                //Utils::ArrayDisplay($objParticipant->getFeeFullUnserialize());
                $resultPrice = 0;
                $textPrice = '';
                $arrayTextPrice = array();

                $arrayPrice2Value = array();

                $objParticipant->setFeeFull(serialize($arrayFee));
                $arrayFeeForCalculation = $arrayFee;
                if (isset($arrayFeeForCalculation['disc'])) {
                    unset($arrayFeeForCalculation['disc']);
                }
                if (Request::GetPost('conference_fee') == 5) {
                    $resultPrice = RegistrationFormSettings::GetOneDayPrice(Request::GetPost('conference_fee_disc'));
                    foreach ($arrayFeeForCalculation as $feeKey => $feeValue) {
                        if ($feeValue == 5) {
                            unset($arrayFeeForCalculation[$feeKey]);
                        }
                    }
                }
                foreach ($arrayObjParameters as $objParam) {
                    if (in_array($objParam->GetId(), $arrayFeeForCalculation) != '') {
                      if (Request::GetPost('conference_fee_disc') == 2) {
                        if($objParam->GetId() != 2 || $_POST['fee_room1'] != null){
                            $resultPrice = $resultPrice + $objParam->getPrice();
                        }
                      } else {
                        
                        /*
                         * TODO: poprawić disc ma być z innego pola 
                         * 'disc' => Request::GetPost('conference_fee') na 'disc' => Request::GetPost('conference_fee_disc') ale nadać value inne niż 2 bo 
                         * if (in_array($objParam->GetId(), $arrayFee))  wyszukuje 2 i ododaje jako dodatkowy pokój :( 
                         * jakieś value="10" albo inne rozwiazanie 
                         * 
                         */
                        
                        // Jesli zmienie się data to zmienić na zwykłą cenę 
                        $resultPrice = $resultPrice + $objParam->getPriceProm();
                        //$resultPrice = $resultPrice + $objParam->getPrice();
                      }
                    }
//                                    tutaj policzę sobie całość
                }
                
                $objParticipant->setPrice($resultPrice);
                $objParticipant->setDateAdd(Utils::GetNowDate());
                $idObj = MfParticipantDAL::Save($objParticipant);
                
                //Utils::ArrayDisplay($resultPrice);
                $textPrice .= '<p>Razem: ' . number_format($resultPrice, 2, ".", "") . '</p>';
                $arrayTextPrice['Razem'] = number_format($resultPrice, 2, ".", "");
//				Utils::ArrayDisplay($textPrice);
                //Utils::ArrayDisplay($arrayTextPrice);
                //Utils::ArrayDisplay('wynik:'.$resultPrice);
                //$this->smarty->assign('message', $data['message']);
                $this->smarty->assign('email', $data['email']);
                $this->smarty->assign('post', $data);
                $this->smarty->assign('textPrice', $textPrice);
                //$this->smarty->assign('name', $post['name']);
//				$textPrice = SessionProxy::GetValue("textPrice");
//				$arrayTextPrice = SessionProxy::GetValue("arrayTextPrice");
//				$formData = SessionProxy::GetValue("formData");
                $this->smarty->assign('formData', $data);
                $this->smarty->assign('textPrice', $textPrice);
                $this->smarty->assign('arrayTextPrice', $arrayTextPrice);
                $this->smarty->assign('arrayFee', $arrayFee);
                $this->smarty->assign('discPrice', $arrayFee['disc']);
                $this->smarty->assign('resultPrice', $resultPrice);
                $this->smarty->assign('arrayObjParameters', $arrayObjParameters);
                $this->smarty->assign('objParticipant', $objParticipant);

                $this->smarty->assign('days', isset($data['days']) ? $data['days'] : '');
                $this->smarty->assign('participationDays', $participationDays);

                
                $txtmessage = '';
                $txtmessage .= $this->smarty->fetch('partial/Index/IndexSent.tpl');
                $txtmessage .= '';

                $mail = new PHPMailer();
                $mail->PluginDir = 'core/lib/phpmailer/';
                $mail->CharSet = "utf-8";
                $mail->Subject = "Formularz zgloszenia";
                $mail->SMTPAuth = true;
                $mail->Mailer = 'mail';
                $mail->Host = Registry::Get('mail_host');
                $mail->Port = 587;
                $mail->IsHTML(true);
                $mail->From = Registry::Get('mail_from');
                $mail->FromName = Registry::Get('name_from');
                $mail->Username = Registry::Get('user_smtp');
                $mail->Password = Registry::Get('password_smtp');
                $mail->AddAddress(Registry::Get('address_to'), Registry::Get('name_to'));
                $mail->AddAddress(Registry::Get('address_to_2'), Registry::Get('name_to_2'));

                $mail->AddAddress($data['email'], $data['name'] . ' ' . $data['surname']);

                $mail->Body = $txtmessage;

                $mail->Send();
                //Utils::ArrayDisplay($mail);
                //Utils::ArrayDisplay($txtmessage);
                SessionProxy::SetValue("qlfon", $idObj);
                SessionProxy::SetValue("formData", $data);
                SessionProxy::SetValue("textPrice", $textPrice);
                SessionProxy::SetValue("arrayTextPrice", $arrayTextPrice);

                $this->smarty->assign('days', $participationDays);

                SessionProxy::SetValue("infoSent", Dictionary::Translate('message_sent'));
                SessionProxy::SetValue("days", $participationDays);

                //$_POST = array();
                //Utils::ArrayDisplay($arrayTextPrice);
                //Utils::ArrayDisplay($_SESSION);
                $this->addRedirectInfo(Dictionary::Translate('message_sent'), 'info', Router::GenerateUrl('current', array()), 0);
            }
        }



        //---Koniec-Kalakulator
        //Utils::ArrayDisplay($arrayGroupParam);
        

        //Utils::ArrayDisplay($_POST);
    }

    public function AjaxFormAction($param) {
        $this->SetAjaxRender();
        $type = Request::GetPost('type');
        $dalData = MfParametersDAL::GetDalDataObj();
        $dalData->addCondition('type', $type);
        $dalData->addCondition('publication', 1);
        $dalData->setSortBy('sort');

        $arrayObjParameters = MfParametersDAL::GetResult($dalData);
        //Utils::ArrayDisplay($arrayObjParameters);
        //===grupowanie====
        $arrayParam = array();
        $arrayGroupParam = array();
        foreach ($arrayObjParameters as $objParam) {
            $idLink = $objParam->GetLinkId();
            $arrayGroupParam[$objParam->GetLinkId()][] = $objParam;
        }
        $this->smarty->assign('arrayObjParameters', $arrayObjParameters);
        $this->smarty->assign('arrayGroupParam', $arrayGroupParam);
        $this->smarty->assign('type', $type);
    }

    public function SearchAction($param) {
        //Art
        $search = trim(Request::GetPost('search'));
        $arraySearch = explode(' ', $search);

        $dalDataArt = SimpleArticle_MfArticleDAL::GetDalDataObj();
        if (count($arraySearch) > 0) {
            $where = ' ( ';
            foreach ($arraySearch as $key => $search) {
                $where .= $key == 0 ? '' : ' OR ';
                $where .= ' mf_article_description.title LIKE "%' . Utils::AddSlashes($search) . '%" ';
                $where .= ' OR mf_article_description.description LIKE "%' . Utils::AddSlashes($search) . '%" ';
            }
            $where .= ' ) ';
            //Utils::ArrayDisplay($where);
            $dalDataArt->addCondition(' ', $where, ' ');
        }
        $dalDataArt->setJoin(array('SimpleArticle_MfArticleDescription' => ' LEFT JOIN mf_article_description ON mf_article.id_mf_article=mf_article_description.id_mf_article'));
        $arrayObjArt = SimpleArticle_MfArticleDAL::GetResult($dalDataArt);

        $arrayObjArtStr = array();
        foreach ($arrayObjArt as $objArt) {
            $dalDataStr = StructureDAL::GetDalDataObj();
            $dalDataStr->addCondition('id_content', $objArt->GetId());
            $obStr = StructureDAL::GetResult($dalDataStr);
            if (isset($obStr[0])) {
                $objArt->setStructure($obStr[0]);
                $arrayObjArtStr[] = $objArt;
            }
        }
        $this->smarty->assign('arrayObjArtStr', $arrayObjArtStr);
        //Utils::ArrayDisplay($arrayObjArtStr);
    }

    /**
     * Wysyłka
     *
     * @param array $param
     */
    public function AjaxSendMessageAction($param) {
        header('Content-Type: text/html; charset=utf-8');
        $this->SetAjaxRender();
        $this->smarty->assign('error', '');
        $this->smarty->assign('wrongPhone', '');
        $this->smarty->assign('wrongEmail', '');
        $this->smarty->assign('success', '');

        //Utils::ArrayDisplay($_POST);
        $validator = new Validator($_POST);
        $errorList = '';
        $error = '';
        $empty = '';
        $wrongEmail = '';
        $wrongPhone = '';
        if (!$validator->IsEmpty('name', '')) {
            $empty = " Podpis </ br>";
        }
        if (!$validator->IsEmpty('temat', '')) {
            $empty = " Temat </ br>";
        }

        if (!$validator->IsEmpty('email', '')) {
            $empty .= " Email ";
        } else {
            if (!$validator->IsEmailAddress('email', '')) {
                $wrongEmail = " Podany adres email jest niepoprawny.";
                $this->smarty->assign('wrongEmail', $wrongEmail);
            }
        }
        //		if (!$validator->CheckCaptcha('captcha', '')) {
        //			$empty .= " Treść Captcha </ br>";
        //		}



        if ($empty) {
            $errorList = true;
        }
        //Utils::ArrayDisplay($empty);
        //Utils::ArrayDisplay($errorList);
        if ($errorList) {
            $this->smarty->assign('error', "Wymagane pola muszą być wypełnione.");
        } elseif ($wrongEmail) {
            
        } elseif ($wrongPhone) {
            
        } else {

            $this->smarty->assign('content', $_POST['content']);
            $this->smarty->assign('email', $_POST['email']);
            $this->smarty->assign('temat', $_POST['temat']);
            $this->smarty->assign('name', $_POST['name']);
            //$this->smarty->assign('typ', $_POST['typ']);
            //$this->smarty->assign('city', $_POST['city']);
            $txtmessage = $this->smarty->fetch('partial/Index/MailTxt.tpl');

            $mail = new PHPMailer();
            $mail->CharSet = "utf-8";
            $mail->Subject = FROM_NAME_MAIL . "  - " . $_POST['temat'];
            $mail->SMTPAuth = true;
            $mail->Mailer = 'smtp';
            $mail->Host = HOST_MAIL;
            $mail->Port = 25;
            $mail->From = FROM_MAIL;
            $mail->FromName = FROM_NAME_MAIL;
            $mail->Username = USER_MAIL;
            $mail->Password = PASS_MAIL;

            $mail->IsHTML(true);

            //$mail -> AddAddress(FORM_MAIL, FROM_NAME_MAIL);
            $mail->AddBCC("studio@aem.pl", "AEM");

            $mail->Body = $txtmessage;

            $mail->Send();
            $this->smarty->assign('success', 'Wiadomość została wysłana');
        }
    }

    /**
     * Wyswietlanie obrazka captcha
     */
    public function CaptchaAction() {
        //$this->disableTemplates = true;
        $this->SetAjaxRender();
        include(PATH_CORE . '/plugins/Captcha.php');
        $word = rand(2, 9) . rand(2, 9) . rand(2, 9) . rand(2, 9) . rand(2, 9);

        setcookie(CAPTCHA_COOKIE_NAME, (md5(strtolower($word) . CAPTCHA_SEED)));
        //session_start();
        //$_SESSION['captcha'] = $word;
        $image = confirm($word);
        $this->content = $image;
        //die();
    }

    public function AjaxRegisterCaptchaCheckAction($param) {
        $this->setAjaxRender();
        $data = array('captcha' => Request::GetGet('captcha', true));
        $validator = new Validator($data);
        $validator->CheckCaptcha('captcha', '');
        $errors = $validator->GetErrorList();
        $this->content = empty($errors) ? "true" : "false";
    }

    public function NewsletterAction($param) {
        //$this->setAjaxRender();
        if (isset($_POST['send'])) {

            $dalData = MfSubscriptionDAL::GetDalDataObj();
            $objSubscripton = new MfSubscription();
            $objSubscripton->setEmail($_POST['email_newsletter']);
            $objSubscripton->setDateAdd(Utils::GetNowDate());

            $dalData->setObj($objSubscripton);
            MfSubscriptionDAL::Save($objSubscripton);

            $this->addRedirectInfo(Dictionary::Translate('Email has been added'), null, $_POST['urlFrom'], 0);
        } else {
            //	$this->addRedirectInfo(Dictionary::Translate('message_sent'), null, $_POST['urlFrom'], 0);
        }
    }

    public function SubsiteAction($param) {
        try {
            $dalData = StructureDAL::GetDalDataObj();
            $dalData->setCondition(array('mf_structure.lang' => $param['lang'], 'mf_structure.publication' => '1', 'id_parent' => $param['idStructure']));
            $dalData->setSortBy('sort');
            $dalData->setJoin(array('SimpleArticle_MfArticleDescription' => ' LEFT JOIN mf_article_description ON mf_article_description.id_mf_article=mf_structure.id_content'));
            $arrayObjSubsite = StructureDAL::GetResult($dalData);
            $this->smarty->assign('arrayObjSubsite', $arrayObjSubsite);
            //Utils::ArrayDisplay($arrayObjSubsite);
        } catch (Exception $e) {
            Utils::ArrayDisplay($e);
        }
    }

    public function PlayerAction($param) {
        $this->SetAjaxRender();
    }

    public function MapsAction($param) {
        //$this->SetAjaxRender();
    }

    public function TestAction($param) {
        Utils::ArrayDisplay('test');
        $this->smarty->assign('indexSG', false);
        //$this->SetAjaxRender();
    }

    /**
     * Czesc wspolna wszystkich podstron
     *
     */
    public function PreDispatch($param) {

        //$this->AddScript('swfobject.js');
        $this->smarty->assign('lang', $param['lang']);
        $this->smarty->assign('indexSG', true);
        $this->Run($param);


        $this->RunShared('MenuBox', $param);
        //$this->RunShared('TagCloudBox', $param);
        //$this->RunShared('News', $param);
        //$this->RunShared('CustomerBox', $param);
        //$this->RunShared('LinksBox', $param);
    }

    public function PostDispatch($param) {
        
    }

}

?>
