<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if($_SESSION['sml_si']!=session_id()) {
    die();
}
require_once("../../db/connection.php");
require_once("../functions.php");
session_write_close();
$id_map = (int)$_POST['id_map'];
if(isset($_POST['type'])) {
    $type = $_POST['type'];
} else {
    $type = 'all';
}
$array = array();
if(empty($id_map)) {
    $query = "SELECT id,file,id_map FROM sml_media_library WHERE id_map IS NULL ORDER BY id DESC;";
} else {
    $query = "SELECT id,file,id_map FROM sml_media_library WHERE id_map=$id_map OR id_map IS NULL ORDER BY id DESC;";
}
$result = $mysqli->query($query);
if($result) {
    if($result->num_rows>0) {
        while($row=$result->fetch_array(MYSQLI_ASSOC)) {
            $row['from']='media_library';
            if(empty($row['id_map'])) $row['id_map']='';
            $path_file = __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'viewer'.DIRECTORY_SEPARATOR.'media'.DIRECTORY_SEPARATOR.$row['file'];
            if(file_exists($path_file)) {
                $row['count']=0;
                $ext = explode('.',$row['file']);
                $ext = strtolower(end($ext));
                switch ($type) {
                    case 'all':
                        $array[]=$row;
                        break;
                }
            }
        }
    }
}
$query = "SELECT 0 as id,image as file FROM sml_images WHERE id_marker IN (SELECT id FROM sml_markers WHERE id_map=$id_map) ORDER BY id DESC;";
$result = $mysqli->query($query);
if($result) {
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
            if (substr($row['file'], 0, 5) === 'media') {
                $row['from']='media_library';
            } else {
                $row['from']='marker_images';
            }
            $path_file = __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'viewer'.DIRECTORY_SEPARATOR.'marker_images'.DIRECTORY_SEPARATOR.$row['file'];
            if(file_exists($path_file)) {
                $ext = explode('.',$row['file']);
                $ext = strtolower(end($ext));
                switch ($type) {
                    case 'all':
                        $index = searchForFile($row['file'],$array);
                        if($index!==false) {
                            $array[$index]['count']=$array[$index]['count']+1;
                        } else {
                            $row['count']=1;
                            $array[]=$row;
                        }
                        break;
                }
            }
        }
    }
}
ob_end_clean();
echo json_encode($array);

function searchForFile($file, $array) {
    foreach ($array as $key => $val) {
        if ($val['file'] === $file) {
            return $key;
        }
    }
    return false;
}