<?php
/**
 * Data manipulation for the model
 */
 class ProfileSettingsModel{
     private function getUserTypeById($idUser){
         global $database;

         $sql = "SELECT ut.type
                    FROM ".TABLES['user_types']." ut
                INNER JOIN ".TABLES['rel_user_type']." rut
                    ON rut.idType=ut.id
                WHERE rut.idUser=$idUser";
         $query = $database->query($sql);
         $row = $database->fetchArray($query);

         return $row['type'];
     }

     /**
      * get profile info
      * @param  INT $idUser id user //broker can see data for all users
      * @return HashArray   user profile information including company information
      */
     public function getProfileInfo($idUser){
         global $database, $user;
         $userType = $user->getUserType();
         $targetUserType = ($userType === USER_TYPES['BROKER'] && $idUser != 0 ) ? $this->getUserTypeById($idUser) : $userType;
         $idUser = $database->escapeValue($idUser);
         if( intval($idUser) === 0){
             $idUser = $user->getUserId();
         }
         $addresHelper = new AddressHelper();

         $sql = "SELECT ui.id,
                        ui.name,
                        ui.phone,
                        u.mail,
                        u.isCompanyAdmin,
                        u.idCompany,
                        ut.idType AS idUserType,
                        c.name AS companyName,
                        c.vatCode
                FROM ".$user->getTableByUser($targetUserType)." ui
                INNER JOIN ".TABLES['users']." u
                ON u.id=ui.idUser
                INNER JOIN ".TABLES['rel_user_type']." ut
                ON ut.idUser=u.id
                LEFT OUTER JOIN ".TABLES['company']." c
                ON u.idCompany=c.id
                WHERE u.id=$idUser
                ";
         $query = $database->query($sql);
         $row = $database->fetchArray($query);
         if($row){
             $row['phone'] = STRING_START.$row['phone'];
             if($userType === USER_TYPES['CUSTOMER']){
                 $row['profileAddresses'] = $addresHelper->getDeliveryAddress();
                 $row['billingAddresses'] = $addresHelper->getBillingAddress();
             }
             $row['userType'] = $userType;
         }

         return $row;
     }

     /**
      * save profile information
      * @param  INT $idUser         id user
      * @param  Object $profile     profile information to save
      * @return Array               save messages
      */
     public function saveProfileInfo($idUser, $profile){
         global $database, $user;
         $profile = json_decode($profile);
         $userHelper = new UsersHelper();
         $userType = $user->getUserType();
         $targetUserType = ($userType === USER_TYPES['BROKER'] && $idUser != 0 ) ? $this->getUserTypeById($idUser) : $userType;
         $idUser = $database->escapeValue($idUser);
         if( intval($idUser) === 0){
             $idUser = $user->getUserId();
         }
         $data = [];

         if(!$idUser || !$userHelper->checkRightsToEdit($idUser)) {
             $err_mes = [
                 'code' => 'error',
                 'message' => 'INVALID_USER'
             ];
             $data['messages'][] = $err_mes;

             return $data;
         }

         if(!$profile){
             $err_mes = [
                 'code' => 'error',
                 'message' => 'INVALID_PROFILE_DATA'
             ];
             $data['messages'][] = $err_mes;

             return $data;
         }

         $checkMessage = $userHelper->validateUserData('edit', $profile);
         if(!empty($checkMessage)){
             return $checkMessage;
         }

         $sql = "UPDATE ".$user->getTableByUser($targetUserType)."
                    SET name='".$profile->name."',
                    phone='".$profile->phone."'
                WHERE id=".$profile->id;

         $query = $database->query($sql);

         if($database->affectedRows()) {
             $mes = [
                 'code' => 'success',
                 'message' => 'PROFILE_UPDATED'
             ];
         }else{
             $mes = [
                 'code' => 'warning',
                 'message' => 'PROFILE_NOT_CHANGED'
             ];
         }

         $data['messages'][] = $mes;

         return $data;
     }

     /**
      * save company information
      * @param  Object $companyInfo copmany information
      * @return Arary               save messages
      */
     public function saveCompanyInfo($companyInfo){
         global $database, $user;
         $companyInfo = json_decode($companyInfo);
         $userHelper = new UsersHelper();
         $data = [];

         if(!$userHelper->checkRightsToEditCompany($companyInfo->idCompany)){
             $err_mes = [
                 'code' => 'error',
                 'message' => 'NOT_COMPANY_ADMIN'
             ];
             $data['messages'][] = $err_mes;

             return $data;
         }

         $checkMessage = $userHelper->validateCompanyData($companyInfo);
         if(!empty($checkMessage)){
             return $checkMessage;
         }

         $sql = "UPDATE ".TABLES['company']."
                    SET name='".$companyInfo->companyName."',
                    vatCode='".$companyInfo->vatCode."'
                WHERE id=".$companyInfo->idCompany;

         $query = $database->query($sql);

         if($database->affectedRows()) {
             $mes = [
                 'code' => 'success',
                 'message' => 'COMPANY_UPDATED'
             ];
         }else{
             $mes = [
                 'code' => 'warning',
                 'message' => 'COMPANY_NOT_CHANGED'
             ];
         }

         $data['messages'][] = $mes;

         return $data;
     }

     /**
      * remove delivery address
      * @param  INT $idProfileAddress id delivery address
      * @return Array                 update message
      */
     public function removeProfileAddress($idProfileAddress){
         $addresHelper = new AddressHelper();

         return $addresHelper->removeProfileAddress($idProfileAddress);
     }

     /**
      * save delivery address
      * @param  Object $profileAddress   delivery address information
      * @return Array                    update message
      */
     public function  saveProfileAddress($profileAddress){
         $addresHelper = new AddressHelper();

         return $addresHelper->saveProfileAddress($profileAddress);
     }

     /**
      * remove billing address
      * @param  INT $idBillingAddress   billing address information
      * @return Array                 update message
      */
     public function removeBillingAddress($idBillingAddress){
         $addresHelper = new AddressHelper();

         return $addresHelper->removeBillingAddress($idBillingAddress);
     }

     /**
      * save billing address
      * @param  INT    $idCompany        id for company
      * @param  Object $billingAddress   billing address information\
      * @return Array                    update message
      */
     public function saveBillingAddress($idCompany, $billingAddress){
         $addresHelper = new AddressHelper();

         return $addresHelper->saveBillingAddress($idCompany, $billingAddress);
     }

     /**
      * get countires
      * @return Array list of countries
      */
     public function getCoutnries(){
         $countries= new Countries();

         return $countries->getCountries();
     }
 }
