<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
require_once("../../db/connection.php");
require_once("../../backend/functions.php");
$id_map = (int)$_POST['id_map'];
$id_marker = (int)$_POST['id_marker'];
$auth_settings = sml_get_viewer_auth_settings($id_map);
$id_user = ((int)$auth_settings['viewer_auth_mode']>0) ? sml_get_viewer_user_id() : null;
if(empty($id_user)) {
    session_write_close();
    echo json_encode(array("status"=>"auth_required"));
    exit;
}
session_write_close();
$authorized = false;
$query_check = "SELECT id FROM sml_markers WHERE id=? AND id_map=? AND id_user=? AND to_validate=1 LIMIT 1;";
if($smt_check = $mysqli->prepare($query_check)) {
    $smt_check->bind_param('iii',$id_marker,$id_map,$id_user);
    $smt_check->execute();
    $result_check = get_result($smt_check);
    if(count($result_check)==1) {
        $authorized = true;
    }
}
if(!$authorized) {
    echo json_encode(array("status"=>"auth_required"));
    exit;
}
$name = strip_tags($_POST['name']);
$street = strip_tags($_POST['street']);
$city = strip_tags($_POST['city']);
$postal_code = strip_tags($_POST['postal_code']);
$country = strip_tags($_POST['country']);
$county = strip_tags($_POST['county']);
$state = strip_tags($_POST['state']);
$website = strip_tags($_POST['website']);
$phone = strip_tags($_POST['phone']);
$whatsapp = strip_tags($_POST['whatsapp']);
$email = strip_tags($_POST['email']);
$hours = $_POST['h_desc'];
$description = convertUrlsToLinks($_POST['description']);
$lat = str_replace(",",".",$_POST['lat']);
$lon = str_replace(",",".",$_POST['lon']);
$array_images = isset($_POST['array_images']) && is_array($_POST['array_images']) ? $_POST['array_images'] : array();
$category = isset($_POST['category']) && is_array($_POST['category']) ? $_POST['category'] : array();
$field_1 = convertUrlsToLinks(strip_tags($_POST['field_1']));
$field_2 = convertUrlsToLinks(strip_tags($_POST['field_2']));
$field_3 = convertUrlsToLinks(strip_tags($_POST['field_3']));
$field_4 = convertUrlsToLinks(strip_tags($_POST['field_4']));
$field_5 = convertUrlsToLinks(strip_tags($_POST['field_5']));
$field_6 = convertUrlsToLinks(strip_tags($_POST['field_6']));
$field_7 = convertUrlsToLinks(strip_tags($_POST['field_7']));
$field_8 = convertUrlsToLinks(strip_tags($_POST['field_8']));
$field_9 = convertUrlsToLinks(strip_tags($_POST['field_9']));
$field_10 = convertUrlsToLinks(strip_tags($_POST['field_10']));
$field_11 = convertUrlsToLinks(strip_tags($_POST['field_11']));
$field_12 = convertUrlsToLinks(strip_tags($_POST['field_12']));
$field_13 = convertUrlsToLinks(strip_tags($_POST['field_13']));
$field_14 = convertUrlsToLinks(strip_tags($_POST['field_14']));
$field_15 = convertUrlsToLinks(strip_tags($_POST['field_15']));
$field_16 = convertUrlsToLinks(strip_tags($_POST['field_16']));
$field_17 = convertUrlsToLinks(strip_tags($_POST['field_17']));
$field_18 = convertUrlsToLinks(strip_tags($_POST['field_18']));
$field_19 = convertUrlsToLinks(strip_tags($_POST['field_19']));
$field_20 = convertUrlsToLinks(strip_tags($_POST['field_20']));
$query = "UPDATE sml_markers SET name=?,street=?,city=?,postal_code=?,country=?,state=?,county=?,website=?,phone=?,whatsapp=?,email=?,hours=?,description=?,lat=?,lon=?,extra_field_value_1=?,extra_field_value_2=?,extra_field_value_3=?,extra_field_value_4=?,extra_field_value_5=?,extra_field_value_6=?,extra_field_value_7=?,extra_field_value_8=?,extra_field_value_9=?,extra_field_value_10=?,extra_field_value_11=?,extra_field_value_12=?,extra_field_value_13=?,extra_field_value_14=?,extra_field_value_15=?,extra_field_value_16=?,extra_field_value_17=?,extra_field_value_18=?,extra_field_value_19=?,extra_field_value_20=? WHERE id=? AND id_map=? AND id_user=? AND to_validate=1;";
$status = false;
if($smt = $mysqli->prepare($query)) {
    $types = str_repeat('s',35).'iii';
    $smt->bind_param($types,$name,$street,$city,$postal_code,$country,$state,$county,$website,$phone,$whatsapp,$email,$hours,$description,$lat,$lon,$field_1,$field_2,$field_3,$field_4,$field_5,$field_6,$field_7,$field_8,$field_9,$field_10,$field_11,$field_12,$field_13,$field_14,$field_15,$field_16,$field_17,$field_18,$field_19,$field_20,$id_marker,$id_map,$id_user);
    $status = $smt->execute();
}
if($status) {
    $query = "DELETE FROM sml_markers_categories_assoc WHERE id_marker=?;";
    if($smt = $mysqli->prepare($query)) {
        $smt->bind_param('i',$id_marker);
        $smt->execute();
    }
    foreach($category as $cat) {
        $cat = (int)$cat;
        $query = "INSERT INTO sml_markers_categories_assoc(id_marker,id_category) VALUES(?,?);";
        if($smt = $mysqli->prepare($query)) {
            $smt->bind_param('ii',$id_marker,$cat);
            $smt->execute();
        }
    }
    $main = 1;
    $query_count = "SELECT COUNT(id) as total_images FROM sml_images WHERE id_marker=?;";
    if($smt_count = $mysqli->prepare($query_count)) {
        $smt_count->bind_param('i',$id_marker);
        $smt_count->execute();
        $result_count = get_result($smt_count);
        if(count($result_count)==1) {
            $row_count = array_shift($result_count);
            if((int)$row_count['total_images']>0) $main = 0;
        }
    }
    foreach($array_images as $image) {
        $image = basename($image);
        $source = dirname(__FILE__).'/../marker_images_tmp/'.$image;
        $source_thumb = dirname(__FILE__).'/../marker_images_tmp/thumb/'.$image;
        $dest = dirname(__FILE__).'/../marker_images/'.$image;
        $dest_thumb = dirname(__FILE__).'/../marker_images/thumb/'.$image;
        if(file_exists($source) && file_exists($source_thumb)) {
            copy($source,$dest);
            copy($source_thumb,$dest_thumb);
            unlink($source);
            unlink($source_thumb);
            $query = "INSERT INTO sml_images(id_marker,id_user,main,image) VALUES(?,?,?,?);";
            if($smt = $mysqli->prepare($query)) {
                $smt->bind_param('iiis',$id_marker,$id_user,$main,$image);
                $smt->execute();
            }
            $main = 0;
        }
    }
    echo json_encode(array("status"=>"ok","id_marker"=>$id_marker));
} else {
    echo json_encode(array("status"=>"error","error"=>$mysqli->error));
}

function convertUrlsToLinks($text) {
    $pattern = '/\b((http(s)?:\/\/)|(www\.))([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3})(:[0-9]{1,5})?(\/[^\s<]*)?\b/i';
    $callback = function ($matches) use ($text) {
        $url = $matches[0];
        if (preg_match('/<a[^>]*href=["\'].*' . preg_quote($url, '/') . '.*["\'][^>]*>/i', $text)) {
            return $url;
        }
        if (!preg_match('/^(http(s)?:\/\/)/', $url)) {
            $url = 'http://' . $url;
        }
        return '<a href="' . $url . '" target="_blank">' . $matches[0] . '</a>';
    };
    return preg_replace_callback($pattern, $callback, $text);
}
