<?php
defined('BASEPATH') or exit('No direct script access allowed');

class LifeModel extends MY_Model
{

    public $ca_parent;
    public $ca_title;
    public $ca_slug;
    public $ca_order;
    public $ca_hide;
    public $ca_trend;
    public $ca_hide_section;

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function saveCmTv($data)
    {
        $inserted = [];

        foreach ($data->videos as $v) {
            $publishedAt = date('Y-m-d H:i:s', strtotime($v->publishedAt));
            $v = (object) array_map(function ($val) {
                return is_null($val) ? "" : $val;
            }, (array) $v);
            $video = [
                'category_idx' => $data->categoryId,
                'channel_idx' => 0,
                'life_type' => 3,
                'head_title' => '',
                'title' => $this->encode($v->title),
                'sub_title' => '',
                'main_img' => $v->thumbnails->medium->url,
                'video_url' => 'https://www.youtube.com/embed/' . $v->id,
                'video_playtime' => '',
                'content' => $this->encode(nl2br($v->description)),
                'org_url' => 'https://youtu.be/' . $v->id,
                'tag' => $v->title,
                'partner_idx' => $data->editorId,
                'editor_name' => $data->categoryTitle,
                'hit_count' => 0,
                'like_count' => 0,
                'comment_count' => 0,
                'share_count' => 0,
                'popular_count' => 0,
                'write_id' => 'developer',
                'write_name' => $data->categoryTitle,
                'reg_id' => 'bot.yt.' . $v->id,
                'reg_date' => $publishedAt,
                'update_id' => $publishedAt,
                'update_date' => $publishedAt,
                'is_display' => 'Y',
                'display_date' => $publishedAt,
                'is_del' => 'N',
            ];
            $video['content'] = '<p style="line-height: 1.8;margin-top:30px"><span style="font-family: 나눔고딕코딩, NanumGothicCoding, sans-serif; font-size: 11pt;">' . $video['content'] . '</span></p>';
            $lifeExists = $this->db->where('reg_id',  $video['reg_id'])->where('category_idx',  $video['category_idx'])->get('life');
            if (!$lifeExists->num_rows()) {
                $this->db->insert('life', $video);
                array_push($inserted, $this->db->insert_id());
            } else {
                $this->db->where('reg_id',  $video['reg_id'])->update('life', $video);
                array_push($inserted, $lifeExists->row()->idx);
            }
        }
        return $inserted;
    }

    /**
     * Encode emoji in text
     * @param string $text text to encode
     */
    public static function encode($text)
    {
        return self::convertEmoji($text, "ENCODE");
    }

    /**
     * Decode emoji in text
     * @param string $text text to decode
     */
    public static function decode($text)
    {
        return self::convertEmoji($text, "DECODE");
    }

    private static function convertEmoji($text, $op)
    {
        if ($op == "ENCODE") {
            return preg_replace_callback('/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{1F000}-\x{1FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F9FF}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F9FF}][\x{1F000}-\x{1FEFF}]?/u', array('self', "encodeEmoji"), $text);
        } else {
            return preg_replace_callback('/(\\\u[0-9a-f]{4})+/', array('self', "decodeEmoji"), $text);
        }
    }

    private static function encodeEmoji($match)
    {
        return str_replace(array('[', ']', '"'), '', json_encode($match));
    }

    private static function decodeEmoji($text)
    {
        if (!$text) return '';
        $text = $text[0];
        $decode = json_decode($text, true);
        if ($decode) return $decode;
        $text = '["' . $text . '"]';
        $decode = json_decode($text);
        if (count($decode) == 1) {
            return $decode[0];
        }
        return $text;
    }
}
