<?php
/**
 * The model for PageListItemData
 * @author Rihards Silins <rihards.silins@mtcmedia.co.uk>
 * @copyright MTC media Ltd
 * @version 5 14/05/2016
 */
namespace Mtc\Cms\Models;

use Illuminate\Database\Capsule\Manager as Capsule;

class PageListItemData extends \Illuminate\Database\Eloquent\Model
{
    /**
     * Indicates the db table of the model
     * @var string
     */
    protected $table = "page_list_item_data";
    /**
     * Indicates if the model should be timestamped.
     * @var bool
     */
    public $timestamps = false;

    /**
     * Load a PageListItemData object properties
     * @param int $id
     * @param string $name
     * @param int $page_list_item_id
     * @param string $language
     * @return PageListItemData Object
     */
    public static function getMultiLanguage($id, $name, $page_list_item_id, $language)
    {
        if (!empty($language)) {
            $page_list_item_data = self::where("page_list_item_id", $page_list_item_id)
                ->where("name", $name)
                ->where("language", $language)
                ->first();
            if (!empty($page_list_item_data)) {
                return $page_list_item_data;
            }
            $id = self::createDataInLanguage($id, $language);
        }
        return self::find($id);
    }

    /**
     * Create a PageListItemData in a specific language
     * @param int $original_page_list_item_data_id
     * @param string $language
     * @return int $new_page_list_item_data_id
     */
    public static function createDataInLanguage($original_page_list_item_data_id, $language)
    {
        return Capsule::transaction(function () use ($original_page_list_item_data_id, $language) {
            Capsule::statement("DROP TEMPORARY TABLE IF EXISTS `tmptable_1`;");
            Capsule::statement(
                "CREATE TEMPORARY TABLE `tmptable_1` AS (SELECT * FROM `page_list_item_data` WHERE `id` = :original_page_list_item_data_id);",
                [":original_page_list_item_data_id" => (int)$original_page_list_item_data_id]
            );
            Capsule::statement("UPDATE `tmptable_1` SET `id` = NULL;");
            Capsule::statement("INSERT INTO `page_list_item_data` SELECT * FROM `tmptable_1`;");
            Capsule::statement("SET @new_id = LAST_INSERT_ID();");
            Capsule::statement(
                "UPDATE `page_list_item_data` SET `language` = :language WHERE `id` = @new_id;",
                [":language" => $language]
            );
            Capsule::statement("DROP TEMPORARY TABLE IF EXISTS `tmptable_1`;");
            $result = Capsule::selectOne("SELECT @new_id;");
            return $result->{"@new_id"};
        });
    }

    /**
     * Get a list of PageListItemData of this $page_list_item_id item
     * @param int $page_list_item_id
     * @param string $language
     * @return PageListItemData Object[] $list
     */
    public static function getMultiLanguageList($page_list_item_id, $language)
    {
        // Item data list to be returned
        $list = [];

        // List of name => id of default item data
        $item_data_names = self::where("page_list_item_id", $page_list_item_id)
            ->where('language', '')
            ->get(['id', 'name'])
            ->lists('id', 'name')
        ;

        // Existing language specific item data
        $lang_data_list = self::where('page_list_item_id', $page_list_item_id)
            ->where('language', $language)
            ->get()
            ->keyBy('name')
        ;

        // Loop through all data we should have, create language specific missing
        foreach ($item_data_names as $name => $id) {
            if (empty($lang_data_list[$name])) {
                $list[] = self::find(self::createDataInLanguage($id, $language));
            } else {
                $list[] = $lang_data_list[$name];
            }
        }

        return $list;
    }

    /**
     * Add a PageListItemData or update the current one.
     * @param mixed[] $options
     * @return boom $success
     */
    public function save(array $options = array())
    {
        if (!is_null($this->value)) {
            if (in_array($this->type, array("datetime", "time", "date")) ||
                in_array($this->css_class, array("datetime", "datepicker", "timepicker", "datetimepicker"))) {
                $source_format = "d/m/Y H:i";// default
                if (!is_null($this->settings) && !empty($this->settings)) {
                    $source_format = $this->settings;
                }
                if (($datetime = \DateTime::createFromFormat($source_format, $this->value)) !== false) {
                    $this->datetime_value = $datetime->format('Y-m-d H:i:s');
                }

            }
            $this->int_value = $this->value;
            $this->tinyint_value = $this->value;
            $this->float_value = $this->value;
            $this->varchar_value = $this->value;
        }
        return parent::save($options);
    }
}
