<?php
/**
 * AdminModel
 * Handles everything on the Platform only the SuperAdmin can access.
 */
class AdminModel
{
    /**
     * @return mixed The Settings of the Platform
     */
    public static function getSettings()
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT id,
                       name,
                       value_text,
                       value_int,
                       created,
                       modified
                FROM ".$prefix."settings";
        $query = $database->prepare($sql);
        $query->execute();

        $settings = new stdClass();
        foreach ($query->fetchAll() as $setting) {
            if ($setting->value_int == NULL) {
                $settings->{$setting->name} = $setting->value_text;
            } else {
                $settings->{$setting->name} = $setting->value_int;
            }
        }

        return $settings;
    }

    public static function saveSettings()
    {
        $values = array('MarketRegistrationStatus'      => 'value_int',
                        'MarketName'                    => 'value_text',
                        'MarketClaim'                   => 'value_text',
                        'MarketUsedTheme'               => 'value_text',
                        'MarketAdminEmail'              => 'value_text',
                        'MarketDetailShort'             => 'value_text',
                        'MarketDetail'                  => 'value_text',
                        'MarketDetailLinkText'          => 'value_text',
                        'MarketDetailLink'              => 'value_int',
                        'MarketContactPerson'           => 'value_text',
                        'MarketContactTel'              => 'value_text',
                        'MarketContactFax'              => 'value_text',
                        'MarketContactEmail'            => 'value_text',
                        'MarketContactWeb'              => 'value_text',
                        'MarketAddressStreet'           => 'value_text',
                        'MarketAddressNumber'           => 'value_text',
                        'MarketAddressZipcode'          => 'value_text',
                        'MarketAddressCity'             => 'value_text',
                        'MarketAddressState'            => 'value_text',
                        'MarketAddressCountry'          => 'value_text',
                        'MarketContactLinkText'         => 'value_text',
                        'MarketContactLink'             => 'value_int',);
        $i = 0; $saved = 0;
        foreach($values as $postName => $DBName) {
            if (self::updateSettings($postName,$DBName,Request::post($postName))) {
                $saved++;
            }
            $i++;
        }
        if ($saved == $i) {
            Session::add('feedback_positive',
                         Text::get('FEEDBACK_SETTINGS_UPDATE_SUCCESSFUL'));
        } else {
            Session::add('feedback_negative',
                         Text::get('FEEDBACK_SETTINGS_UPDATE_FAILED'));
        }
    }

    public static function processLogoImage()
    {
        $logo_array   = array('logo_big'        =>  array('width'  => 500,
                                                          'height' => 500),
                              'logo_medium'     =>  array('width'  => 200,
                                                          'height' => 200),
                              'platform_logo'   =>  array('width'  => 100,
                                                          'height' => 100),
                              'logo_small'      =>  array('width'  => 30,
                                                          'height' => 30));
        $result = UploadModel::imageUpload('platform','platform',$logo_array);
        if ($result['success'] == true) {
            if (self::saveImage('MarketLogo',$result['imagePath'])) {
                header("HTTP/1.1 200 OK");
                echo "upload successful";
            } else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "error while saving in db!";
            }
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            if (isset($result['error'])) {
                echo $result['error'];
            } else {
                echo "something went wrong";
            }
        }
    }

    public static function processHeaderImage()
    {
        $header_array = array('header_big'    => array('width'  => 1360,
                                                       'height' => 500),
                              'header_medium' => array('width'  => 950,
                                                       'height' => 350),
                              'header_small'  => array('width'  => 543,
                                                       'height' => 200));
        $result = UploadModel::imageUpload('platform','platform',$header_array);
        if ($result['success'] == true) {
            if (self::saveImage('MarketHeader',$result['imagePath'])) {
                header("HTTP/1.1 200 OK");
                echo "upload successful";
            } else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "error while saving in db!";
            }
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            if (isset($result['error'])) {
                echo $result['error'];
            } else {
                echo "something went wrong";
            }
        }
    }

    public static function processBackgroundImage()
    {
        $background_array = array('background_big'    => array('width'  => 3840,
                                                               'height' => 2160),
                                  'background_medium' => array('width'  => 1920,
                                                               'height' => 1080),
                                  'background_small'  => array('width'  => 1280,
                                                               'height' => 720));
        $result = UploadModel::imageUpload('platform','platform',$background_array);
        if ($result['success'] == true) {
            if (self::saveImage('MarketBackground',$result['imagePath'])) {
                header("HTTP/1.1 200 OK");
                echo "upload successful";
            } else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "error while saving in db!";
            }
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            if (isset($result['error'])) {
                echo $result['error'];
            } else {
                echo "something went wrong";
            }
        }
    }

    public static function saveImage($setting_name,$setting_value)
    {
        return self::updateSettings($setting_name,'value_text',$setting_value);
    }

    public static function updateSettings($setting_name,$field_name,$value)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "UPDATE ".$prefix."settings
                SET ".$field_name." = :value,
                    modified = NOW()
                WHERE name = :setting_name
                LIMIT 1";
        $query = $database->prepare($sql);
        $query->bindParam(':value',         $value,                 PDO::PARAM_STR);
        $query->bindParam(':setting_name',  $setting_name,          PDO::PARAM_STR);
        if ($query->execute()) {
            if (in_array($setting_name,array('MarketName',
                                             'MarketAddressZipcode',
                                             'MarketAddressCity',
                                             'MarketDetailShort')) &&
                $query->rowCount() > 0) {
                self::updatePlatformModified();
            }
            return true;
        } else {
            return false;
        }
    }

    public static function updatePlatformModified($id = null)
    {
        $id = (int) $id;
        if ($id != null && is_int($id)) {
            $where = 'WHERE id = '.$id.' LIMIT 1';
        } else {
            $where = '';
        }

        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "UPDATE ".$prefix."platforms
                SET modified = NOW()
                ".$where;
        $query = $database->prepare($sql);

        if ($query->execute()) {
            return true;
        } else {
            return false;
        }
    }

    public static function validateMarketName($marketName)
    {
        if (empty($marketName)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_MARKET_NAME_EMPTY'));
            return false;
        }

        return true;
    }
}
