<?php
date_default_timezone_set('Asia/Tehran');

function yc_get_option($name)
{
    $opt = get_option($name);
    $result = (!empty($opt)) ? $opt : null;
    return $result;
}

function yc_get_post_meta($post_id, $key, $single = true)
{
    $meta = get_post_meta($post_id, $key, $single);
    $meta = (isJson($meta)) ? json_decode($meta, true) : $meta;
    $result = (!empty($meta)) ? $meta : null;
    return $result;
}

function get_imdb_link($id)
{
    $result = '';
    if (!empty($id)) $result = 'https://www.imdb.com/title/' . $id . '/';
    return $result;
}

function get_user_profile($user = null, $url = false, $args = null)
{
    $result = '';
    if (empty($user) || $user == null) $user = 0;
    $result = ($url) ? get_avatar_url($user, $args) : get_avatar($user, 50, '', '', $args);
    return $result;
}

if (!function_exists('get_user_IP')) {
    function get_user_IP()
    {
        $client = false;
        if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
            $client = $_SERVER['HTTP_CLIENT_IP'];
        }
        $forward = false;
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
            $forward = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        $remote = $_SERVER['REMOTE_ADDR'];
        if (filter_var($client, FILTER_VALIDATE_IP)) {
            $ip = $client;
        } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
            $ip = $forward;
        } else {
            $ip = $remote;
        }
        return $ip;
    }
}

function convert_time_to_ago($datetime, $full = false)
{
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'سال',
        'm' => 'ماه',
        'w' => 'هفته',
        'd' => 'روز',
        'h' => 'ساعت',
        'i' => 'دقیقه',
        's' => 'ثانیه',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? '' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' قبل' : 'همین الان';
}

function fix_html_tags($html)
{
    $doc = new DOMDocument();
    $doc->substituteEntities = false;
    $content = mb_convert_encoding($html, 'html-entities', 'utf-8');
    @$doc->loadHTML($content);
    $result = $doc->saveHTML();
    return html_entity_decode($result);
}

function isHTML($string)
{
    return ($string != strip_tags($string));
}

function isJson($string)
{
    if (!is_array($string)) {
        json_decode($string);
        return json_last_error() === JSON_ERROR_NONE;
    } else return false;
}

function validate_url_address($url, $site = null)
{
    $result = false;
    $regex = '#((\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';
    $url = (preg_match('(http://|https://)', $url) === 1) ? strtolower($url) : 'https://' . strtolower($url);
    $result = (@preg_match($regex, $url, $match)) ? true : false;
    if (!empty($site) && $result) {
        $site = strtolower($site);
        $validate = parse_url($url);
        if (!isset($validate['host']) || $validate['host'] == '' || $validate['host'] != $site) $result = false;
    }
    return $result;
}

if (!function_exists('objectToArray')) {
    function objectToArray($d)
    {
        if (is_object($d)) {
            $d = get_object_vars($d);
        }
        if (is_array($d)) {
            return array_map(__FUNCTION__, $d);
        } else {
            return $d;
        }
    }
}

function get_real_post_dllinks($post_id)
{
    $result = null;
    $dlbox_deactive = yc_get_post_meta($post_id, 'deactive_dlbox', true);
    $post_type = get_post_type($post_id);
    $links = array();
    if (!$dlbox_deactive) {
        if ($post_type == 'movies') $links = (!empty($post_id)) ? yc_get_post_meta($post_id, 'movies_dlbox', true) : array();
        else if ($post_type == 'series') $links = (!empty($post_id)) ? yc_get_post_meta($post_id, 'series_dlbox', true) : array();
    }

    if (!empty($links)) {
        $new_links = array();
        if ($post_type == "movies") {
            foreach ($links as $link) {
                $type = (!empty($link['link_type'])) ? $link['link_type'] : '';
                if ($type == 'dub') $new_links['dub'][] = $link;
                elseif ($type == 'sub') $new_links['sub'][] = $link;
                else $new_links['other'][] = $link;
            }
        } elseif ($post_type == "series") {
            foreach ($links as $season_id => $season) {
                $subtype = 0;
                $season_name = (!empty($season['name'])) ? $season['name'] : 'فصل ' . $season_id;
                $items = (!empty($season['items']) && is_array($season['items'])) ? $season['items'] : array();
                $type = (!empty($season['type'])) ? $season['type'] : 'other';
                $quality = (!empty($season['quality'])) ? $season['quality'] : 0;
                $count = (!empty($season['count'])) ? $season['count'] : 0;
                $capacity = (!empty($season['capacity'])) ? $season['capacity'] : 0;
                $price = (!empty($season['price'])) ? $season['price'] : 0;
                if ($type == 'sub') $subtype = (!empty($season['subtype'])) ? $season['subtype'] : 0;
                $new_links[$type][$season_name]['count'] = $count;
                foreach ($items as $item_id => $item) {
                    $item_info = (!empty($item) && is_array($item)) ? $item : array();
                    if (!empty($item_info)) {
                        $item_info['capacity'] = $capacity;
                        $item_info['price'] = $price;
                        $item_name = (!empty($item['title'])) ? $item['title'] : 'قسمت ' . (int) ($item_id + 1);
                        $new_links[$type][$season_name]["episodes"][$item_name][$quality][$subtype] = $item_info;
                    }
                }
            }
        }
        if (!empty($new_links)) {
            $result["type"] = $post_type;
            $result["links"] = $new_links;
        }
    }
    return $result;
}

function get_index_page_streams()
{
    $result = array();
    $queried_object = get_queried_object();
    if (!empty($_GET['ad-s']) && $_GET['ad-s'] == '1') $result['adv_search'] = true;
    else $result['adv_search'] = false;
    if (!empty($queried_object)) {
        $result['term_tax'] = (!empty($queried_object->taxonomy)) ? $queried_object->taxonomy : '';
        if (!empty($result['term_tax'])) {
            $result['term_id'] = (!empty($queried_object->term_id)) ? $queried_object->term_id : '';
            $result['term_name'] = (!empty($queried_object->name)) ? $queried_object->name : '';
            $result['term_description'] = (!empty($queried_object->description)) ? $queried_object->description : '';
        } elseif (is_archive(array('movies', 'series'))) $result['post_type'] = $queried_object->name;
    }
    return $result;
}

function get_the_reading_time(int $post_id = 0)
{
    $content = get_the_content($post_id);
    $word_count = (!empty($content)) ? count(explode(' ', $content)) : 0;
    $readingtime = ceil($word_count / 200);
    $totalreadingtime = $readingtime;
    return $totalreadingtime;
}

function get_email_headers()
{
    $headers = array();
    $headers[]       = 'MIME-Version: 1.0' . "\r\n";
    $headers[]       = 'Content-type: text/html; charset=UTF-8' . "\r\n";
    $headers[]       = "X-Mailer: PHP \r\n";
    $headers[]       = 'From: ' . SITE_URL . "\r\n";
    return $headers;
}

function yascode_send_email($user_id, $title, $content)
{
    $result = false;
    $sendMail = false;
    $headers = get_email_headers();
    if (!empty($user_id)) {
        if (is_numeric($user_id)) {
            $userdata = get_userdata($user_id);
            $email = (empty($userdata->user_email) ? '' : $userdata->user_email);
            if (!empty($email)) $sendMail = wp_mail($email, $title, $content, $headers);
        } elseif (email_exists($user_id)) $sendMail = wp_mail($user_id, $title, $content, $headers);
    }
    if ($sendMail) $result = true;
    return $result;
}

function yascode_jalali_to_gregorian($str, $mod = '/')
{
    $result = '';
    $ex_date = explode($mod, $str);
    $new_date = jalali_to_gregorian($ex_date[0], $ex_date[1], $ex_date[2]);
    $new_date[1] = sprintf('%02d', $new_date[1]);
    $new_date[2] = sprintf('%02d', $new_date[2]);
    $result = implode('-', $new_date);
    return $result;
}

function change_days_to_human($days)
{
    $result = array();
    if ($days % 365 == 0) $year = $days / 365;
    elseif ($days % 30 == 0) $month = $days / 30;
    if (!empty($month)) {
        $result['number'] = $month;
        $result['type'] = 'ماه';
    } else if (!empty($year)) {
        $result['number'] = $year;
        $result['type'] = 'سال';
    } else {
        $result['number'] = $days;
        $result['type'] = 'روز';
    }
    return $result;
}

function get_online_play_link($post_id, $time = null, $season = null, $episode = null)
{
    $result = SITE_URL . '/play/' . $post_id;
    if (!empty($season) && is_numeric($season)) {
        $result .= '/' . $season;
        $result = (!empty($episode) && is_numeric($episode)) ? $result . '/' . $episode : $result . '/1';
    }
    if (!empty($time) && is_numeric($time)) $result .= '/?time=' . $time;
    return $result;
}

function get_file_extension($path)
{
    $qpos = strpos($path, "?");

    if ($qpos !== false) $path = substr($path, 0, $qpos);

    $extension = pathinfo($path, PATHINFO_EXTENSION);

    return $extension;
}
