<?php

class RegistrationFormSettings {

    const DAYS_LODGING = 'registration_form_days_lodging';
    const DAYS_NO_LODGING = 'registration_form_days_no_lodging';
    const VAT_MULTIPLIER = 'registration_form_vat_multiplier';
    const ONE_DAY_PRICE_PROM = 'registration_form_one_day_price_prom';
    const ONE_DAY_PRICE_NORMAL = 'registration_form_one_day_price_normal';

    private static $defaults = array(
        'registration_form_days_lodging' => "3/4 listopada\n4/5 listopada",
        'registration_form_days_no_lodging' => "3 listopada\n4 listopada\n5 listopada",
        'registration_form_vat_multiplier' => '1.23',
        'registration_form_one_day_price_prom' => '1300',
        'registration_form_one_day_price_normal' => '1600',
    );

    private static $priceParameterIds = array(
        'full_conference' => 1,
        'single_room' => 2,
        'accompanying_person' => 3,
        'english_conference' => 4,
        'legacy_one_day' => 5,
    );

    public static function GetSettings() {
        $variables = self::GetVariables();
        $vatMultiplier = self::NormalizeNumber(self::GetVariableValue($variables, self::VAT_MULTIPLIER));

        if (!$vatMultiplier) {
            $vatMultiplier = self::$defaults[self::VAT_MULTIPLIER];
        }

        return array(
            'days_lodging_text' => self::GetVariableValue($variables, self::DAYS_LODGING),
            'days_no_lodging_text' => self::GetVariableValue($variables, self::DAYS_NO_LODGING),
            'days_lodging' => self::ParseList(self::GetVariableValue($variables, self::DAYS_LODGING)),
            'days_no_lodging' => self::ParseList(self::GetVariableValue($variables, self::DAYS_NO_LODGING)),
            'vat_multiplier' => (float)$vatMultiplier,
            'one_day_price_prom' => (float)self::NormalizeNumber(self::GetVariableValue($variables, self::ONE_DAY_PRICE_PROM)),
            'one_day_price_normal' => (float)self::NormalizeNumber(self::GetVariableValue($variables, self::ONE_DAY_PRICE_NORMAL)),
            'prices' => self::GetPriceSettings((float)$vatMultiplier),
        );
    }

    public static function SaveSettings($post) {
        self::SaveVariable(self::DAYS_LODGING, self::NormalizeListText($post[self::DAYS_LODGING]), 'Dni udzialu - jeden dzien z noclegiem');
        self::SaveVariable(self::DAYS_NO_LODGING, self::NormalizeListText($post[self::DAYS_NO_LODGING]), 'Dni udzialu - jeden dzien bez noclegu');
        self::SaveVariable(self::VAT_MULTIPLIER, self::NormalizeNumber($post[self::VAT_MULTIPLIER]), 'Mnoznik VAT dla cen formularza rejestracji');
        self::SaveVariable(self::ONE_DAY_PRICE_PROM, self::NormalizeNumber($post[self::ONE_DAY_PRICE_PROM]), 'Cena netto promocyjna - jeden dzien');
        self::SaveVariable(self::ONE_DAY_PRICE_NORMAL, self::NormalizeNumber($post[self::ONE_DAY_PRICE_NORMAL]), 'Cena netto normalna - jeden dzien');

        foreach (self::$priceParameterIds as $key => $id) {
            if (!isset($post['price'][$id])) {
                continue;
            }

            $objParam = MfParametersDAL::GetById($id);
            if (!$objParam || $objParam->GetId() == '-1') {
                continue;
            }

            $price = isset($post['price'][$id]) ? self::NormalizeNumber($post['price'][$id]) : '';
            $priceProm = isset($post['price_prom'][$id]) ? self::NormalizeNumber($post['price_prom'][$id]) : '';
            $objParam->setPrice($price);
            $objParam->setPriceProm($priceProm);
            MfParametersDAL::Save($objParam);
        }
    }

    public static function Validate($post) {
        $errors = array();
        $required = array(
            self::DAYS_LODGING => 'Podaj dni dla opcji z noclegiem.',
            self::DAYS_NO_LODGING => 'Podaj dni dla opcji bez noclegu.',
            self::VAT_MULTIPLIER => 'Podaj mnoznik VAT.',
            self::ONE_DAY_PRICE_PROM => 'Podaj cene promocyjna za jeden dzien.',
            self::ONE_DAY_PRICE_NORMAL => 'Podaj cene normalna za jeden dzien.',
        );

        foreach ($required as $field => $message) {
            if (!isset($post[$field]) || trim($post[$field]) === '') {
                $errors[$field] = $message;
            }
        }

        foreach (array(self::VAT_MULTIPLIER, self::ONE_DAY_PRICE_PROM, self::ONE_DAY_PRICE_NORMAL) as $field) {
            if (isset($post[$field]) && trim($post[$field]) !== '' && !self::IsNumber($post[$field])) {
                $errors[$field] = 'Pole musi byc liczba.';
            }
        }

        if (isset($post['price']) && is_array($post['price'])) {
            foreach ($post['price'] as $id => $value) {
                if (trim($value) !== '' && !self::IsNumber($value)) {
                    $errors['price_' . $id] = 'Cena musi byc liczba.';
                }
            }
        }

        if (isset($post['price_prom']) && is_array($post['price_prom'])) {
            foreach ($post['price_prom'] as $id => $value) {
                if (trim($value) !== '' && !self::IsNumber($value)) {
                    $errors['price_prom_' . $id] = 'Cena promocyjna musi byc liczba.';
                }
            }
        }

        return $errors;
    }

    public static function GetOneDayPrice($discountType) {
        $settings = self::GetSettings();
        return $discountType == 2 ? $settings['one_day_price_normal'] : $settings['one_day_price_prom'];
    }

    public static function GetVatMultiplier() {
        $settings = self::GetSettings();
        return $settings['vat_multiplier'];
    }

    private static function GetPriceSettings($vatMultiplier) {
        $prices = array();

        foreach (self::$priceParameterIds as $key => $id) {
            $objParam = MfParametersDAL::GetById($id);
            $net = $objParam && $objParam->GetId() != '-1' ? (float)$objParam->GetPrice() : 0;
            $prom = $objParam && $objParam->GetId() != '-1' ? (float)$objParam->GetPriceProm() : 0;

            $prices[$key] = array(
                'id' => $id,
                'name' => $objParam && $objParam->GetId() != '-1' ? $objParam->GetName() : '',
                'price' => $net,
                'price_prom' => $prom,
                'price_vat' => $net * $vatMultiplier,
                'price_prom_vat' => $prom * $vatMultiplier,
            );
        }

        $prices['one_day'] = array(
            'price_prom' => (float)self::GetVariableRaw(self::ONE_DAY_PRICE_PROM),
            'price_normal' => (float)self::GetVariableRaw(self::ONE_DAY_PRICE_NORMAL),
        );

        return $prices;
    }

    private static function GetVariables() {
        $variables = array();
        $db = Registry::Get('db');
        $stmt = $db->execute("select variable,value,description from wp_setup order by variable,value");
        $array = $stmt->FetchAllAssoc();

        foreach ($array as $variable) {
            $variables[$variable['variable']] = array(
                'variable' => $variable['variable'],
                'value' => $variable['value'],
                'description' => $variable['description'],
            );
        }

        return $variables;
    }

    private static function GetVariableValue($variables, $name) {
        if (isset($variables[$name])) {
            return $variables[$name]['value'];
        }

        return self::$defaults[$name];
    }

    private static function GetVariableRaw($name) {
        $variables = self::GetVariables();
        return self::NormalizeNumber(self::GetVariableValue($variables, $name));
    }

    private static function SaveVariable($name, $value, $description) {
        SetupDAL::SaveVariable($name, $value, $description);
    }

    private static function ParseList($text) {
        $text = str_replace(array("\r\n", "\r"), "\n", $text);
        $items = explode("\n", $text);
        $return = array();

        foreach ($items as $item) {
            $item = trim($item);
            if ($item !== '') {
                $return[] = $item;
            }
        }

        return $return;
    }

    private static function NormalizeListText($text) {
        return implode("\n", self::ParseList($text));
    }

    private static function NormalizeNumber($value) {
        return str_replace(',', '.', trim($value));
    }

    private static function IsNumber($value) {
        return is_numeric(self::NormalizeNumber($value));
    }
}

?>
