<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if($_SESSION['sml_si']!=session_id()) {
    die();
}
require(__DIR__.'/ssp.class.php');
require(__DIR__.'/../functions.php');
require(__DIR__.'/../../config/config.inc.php');

$id_map = $_GET['id_map'];
$query = "SELECT g.*,GROUP_CONCAT(DISTINCT gc.id_category) as id_categories,GROUP_CONCAT(DISTINCT c.name) as categories FROM sml_geodata as g LEFT JOIN sml_geodata_categories_assoc as gc ON gc.id_geodata=g.id LEFT JOIN sml_categories as c ON c.id=gc.id_category WHERE g.id_map=$id_map GROUP BY g.id";
$table = "( $query ) t";
$primaryKey = 'id';

$columns = array(
    array(
        'db' => 'id',
        'dt' => 'DT_RowId',
        'formatter' => function( $d, $row ) {
            return $d;
        }
    ),
    array( 'db' => 'file',  'dt' =>0, 'formatter' => function($d,$row) {
        return pathinfo($d, PATHINFO_FILENAME);;
    }),
    array( 'db' => 'file',  'dt' =>1, 'formatter' => function($d,$row) {
        $ext = strtolower(pathinfo($d, PATHINFO_EXTENSION));
        $type = "--";
        switch($ext) {
            case 'json':
            case 'geojson':
                $type = "GeoJSON";
                break;
            case 'kml':
                $type = "KML";
                break;
            case 'kmz':
                $type = "KMZ";
                break;
            case 'gpx':
                $type = "GPX";
                break;
            case 'zip':
                $type = "ShapeFile";
                break;
        }
        return $type;
    }),
    array( 'db' => 'categories',  'dt' =>2, 'formatter' => function($d,$row) {
        return "<button onclick='open_modal_geodata_categories({$row['id']},\"{$row['id_categories']}\")' style='line-height:1;' class='btn btn-sm btn-primary'><i class=\"fas fa-gear\"></i></button>&nbsp;&nbsp;".$d;
    }),
    array( 'db' => 'style',  'dt' =>3, 'formatter' => function($d,$row) {
        return "<button onclick='open_modal_geodata_style({$row['id']},`{$row['style']}`,`{$row['file']}`)' style='line-height:1;' class='btn btn-sm btn-primary'><i class=\"fas fa-gear\"></i></button>";
    }),
    array( 'db' => 'content',  'dt' =>4, 'formatter' => function($d,$row) {
        return "<button onclick='open_modal_geodata_content({$row['id']})' style='line-height:1;' class='btn btn-sm btn-primary'><i class=\"fas fa-heading\"></i></button>".(!empty($d) ? '&nbsp;&nbsp;<i class="fas fa-check"></i>' : '');
    }),
    array( 'db' => 'id',  'dt' =>5, 'formatter' => function($d,$row) {
        return "<button onclick='delete_geodata($d)' style='line-height:1;' class='btn btn-sm btn-danger'><i class=\"fas fa-trash\"></i></button>";
    }),
);

$sql_details = array(
    'user' => DATABASE_USERNAME,
    'pass' => DATABASE_PASSWORD,
    'db' => DATABASE_NAME,
    'host' => DATABASE_HOST);

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);