<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
ob_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
$settings = get_settings();
if(!empty($settings['timezone'])) {
    date_default_timezone_set($settings['timezone']);
}
$id_marker = (int)$_POST['id_marker'];
$id_map = 0;
$query_map = "SELECT id_map FROM sml_markers WHERE id=? LIMIT 1;";
if($smt_map = $mysqli->prepare($query_map)) {
    $smt_map->bind_param('i',$id_marker);
    $smt_map->execute();
    $result_map = get_result($smt_map);
    if(count($result_map)==1) {
        $row_map = array_shift($result_map);
        $id_map = (int)$row_map['id_map'];
    }
}
$auth_settings = sml_get_viewer_auth_settings($id_map);
$viewer_user_id = ((int)$auth_settings['viewer_auth_mode']>0) ? sml_get_viewer_user_id() : null;
session_write_close();
$map_language = strip_tags($_POST['language']);
$array_reviews = array();
$average_rating = 0;
$viewer_reviewed = false;
$array_perc = [0,0,0,0,0];
$query = "SELECT language,language_domain FROM sml_settings LIMIT 1;";
$result = $mysqli->query($query);
if($result) {
    if($result->num_rows==1) {
        $row=$result->fetch_array(MYSQLI_ASSOC);
        if($map_language!='') {
            $language = $map_language;
        } else {
            $language = $row['language'];
        }
        switch($language) {
            case 'pt_BR':
                $lang_code='pt-BR';
                break;
            case 'pt_PT':
                $lang_code='pt-PT';
                break;
            case 'zh_CN':
                $lang_code='zh-CN';
                break;
            case 'zh_TW':
                $lang_code='zh-TW';
                break;
            case 'zh_HK':
                $lang_code='zh-hk';
                break;
            default:
                $lang_code = substr($language, 0, 2);
                break;
        }
        $lang_code_2 = str_replace("_","-",$language);
        if (function_exists('gettext')) {
            if(defined('LC_MESSAGES')) {
                $result = setlocale(LC_MESSAGES, $language);
                if(!$result) {
                    setlocale(LC_MESSAGES, $language.'.UTF-8');
                }
                if (function_exists('putenv')) {
                    $result = putenv('LC_MESSAGES='.$language);
                    if(!$result) {
                        putenv('LC_MESSAGES='.$language.'.UTF-8');
                    }
                }
            } else {
                if (function_exists('putenv')) {
                    $result = putenv('LC_ALL='.$language);
                    if(!$result) {
                        putenv('LC_ALL='.$language.'.UTF-8');
                    }
                }
            }
            $domain = $row['language_domain'];
            $result = bindtextdomain($domain, "../../locale");
            if(!$result) {
                $domain = "default";
                bindtextdomain($domain, "../../locale");
            }
            bind_textdomain_codeset($domain, 'UTF-8');
            textdomain($domain);
        } else {
            if (!function_exists('_')) {
                function _($a) {
                    return $a;
                }
            }
        }
    }
}
$query = "SELECT * FROM sml_reviews WHERE id_marker=? ORDER BY create_date DESC;";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('i',$id_marker);
    $result = $smt->execute();
    if($result) {
        $result = get_result($smt);
        $count = count($result);
        if($count>0) {
            while($row = array_shift($result)) {
                $rating = $row['rating'];
                $array_perc[($rating-1)]++;
                $average_rating = $average_rating+$rating;
                $row['create_date'] = timeAgo($row['create_date']);
                $row['comment'] = nl2br($row['comment']);
                $row['reply'] = nl2br($row['reply']);
                if(empty($row['reply'])) $row['reply'] = '';
                $row['is_owner'] = (!empty($viewer_user_id) && !empty($row['id_user']) && (int)$row['id_user']===(int)$viewer_user_id) ? 1 : 0;
                if($row['is_owner']) {
                    $viewer_reviewed = true;
                }
                unset($row['id_user']);
                $array_reviews[] = $row;
            }
            $average_rating = round($average_rating/$count,1);
            $array_perc[0] = get_percentage($count,$array_perc[0]);
            $array_perc[1] = get_percentage($count,$array_perc[1]);
            $array_perc[2] = get_percentage($count,$array_perc[2]);
            $array_perc[3] = get_percentage($count,$array_perc[3]);
            $array_perc[4] = get_percentage($count,$array_perc[4]);
        }
    }
}
ob_end_clean();
echo json_encode(array("reviews"=>$array_reviews,"average_rating"=>$average_rating,"array_perc"=>$array_perc,"viewer_reviewed"=>$viewer_reviewed));

function get_percentage($total, $number) {
    if ( $total > 0 ) {
        return round(($number * 100) / $total, 2);
    } else {
        return 0;
    }
}

function timeAgo($time_ago) {
    $time_ago = strtotime($time_ago);
    $cur_time   = time();
    $time_elapsed   = $cur_time - $time_ago;
    $days       = round($time_elapsed / 86400 );
    $weeks      = round($time_elapsed / 604800);
    $months     = round($time_elapsed / 2600640 );
    $years      = round($time_elapsed / 31207680 );
    if ($days <= 7) {
        if ($days == 0) {
            return _("Today");
        } elseif ($days == 1) {
            return _("Yesterday");
        } else {
            return sprintf(_("%d days ago"), $days);
        }
    } elseif ($weeks <= 4.3) {
        if ($weeks == 1) {
            return _("1 week ago");
        } else {
            return sprintf(_("%d weeks ago"), $weeks);
        }
    } elseif ($months <= 12) {
        if ($months == 1) {
            return _("1 month ago");
        } else {
            return sprintf(_("%d months ago"), $months);
        }
    } else {
        if ($years == 1) {
            return _("1 year ago");
        } else {
            return sprintf(_("%d years ago"), $years);
        }
    }
}
