set_include_path(".:/usr/lib/php:/usr/local/lib/php:/var/www/html/assets");
require 'test/bd.php';
$xpdo = new xPDO($dsn, $username, $password);

if(isset($_GET['mode']) && $_GET['mode'] == 'delete'){
  mysqli_query($bd, 'DELETE FROM massage WHERE id = ' . (int)$_GET['id']);
  header('Location: spisok-rassyilok', true, 301);
}

if(isset($_GET['mode']) && $_GET['mode'] == 'edit'){
  $sql = 'SELECT * FROM massage WHERE id = ' . (int)$_GET['id'] . ' AND user = \'' . $user . '\'';
  $data = mysqli_query($bd, $sql);
  $edit_row = mysqli_fetch_assoc($data);
  if(!$edit_row)
    die('not found');

  $date_from = UnixToTime($edit_row['dec_time'], $edit_row['tz']);
  //print_r($edit_row);
}

if(isset($_POST['sbt'])){
  $send_phone = $_POST['sender_phone'] ? $_POST['sender_phone'] : '';
  $phone = implode(',', array_map('trim', explode("\r\n", trim($_POST['phone']))));
  $se_phone = $_POST['se_phone'];
  $text = $_POST['text'];
  $time = time();
  $date = tiemUnix($_POST['date'], $_POST['time']);
  //$date_desc = tiemUnix($_POST['date_desc'], $_POST['time_desc']);
  $query = "INSERT INTO `massage`(`time`, `dec_time`, `user_phone`, `se_phone`, `massage`) VALUES ('$time', '$date', '$phone', `$send_phone`, '$text')";
  $xpdo->query($query);
}

function UnixToTime($unix, $tz){
  $unix+=$tz;
  return ['date' => date('Y-m-d', $unix), 'time' => date('H:i', $unix)];
}

function tiemUnix($d,$t){
  $date = $d;
  $date = str_replace('/', '-', $date);
  $date = $date . ' ' . $t . ':00';
  $timestamp = strtotime($date);
  return $timestamp;
}

class TimeZoneList {
  private $timezone_identifiers;
  private $error;

  public function __construct () {
   $this->error = '';
   $needver = '5.2.0';
   if (version_compare(PHP_VERSION, $needver, '<=')) {    
    $this->error = 'Класс TimeZoneList требует PHP версии не ниже '.$needver.'. Ваша версия: '.PHP_VERSION;
    return;
  }
  $this->timezone_identifiers = DateTimeZone::listIdentifiers();
}

public function get_array () {
 $timezones = array ();
 if (!empty($this->error)) return array (0 => $this->error);
 $phpTime = Date("Y-m-d H:i:s");
 foreach ($this->timezone_identifiers as $key=>$value) {
  if (preg_match('/^(Europe|America|Asia|Antartica|Arctic|Atlantic|Indian|Pacific)\//', $value)) {
   $timezone = new DateTimeZone ($value);
   $offset = $timezone->getOffset(new DateTime($phpTime));
   $offsetHours = abs($offset)/3600;
   $offsetString = ($offset < 0 ? '-' : '+');
   if (abs($offsetHours)==1) $label = 'час'; 
   else if (abs($offsetHours)>1 and abs($offsetHours)<5) $label = 'часа';
   else $label = 'часов';
   $timezones[$value] = array (
    'timezone' => $value.' ('.$offsetString.$offsetHours.' '.$label.')',
    'offset' => $offset
  );
 }
}

uasort ($timezones, function ($a, $b) {
  return $a['offset'] != $b['offset'] ? $b['offset'] < $a['offset'] : $b['timezone'] < $a['timezone'];
});

return $timezones;
}

public function get_html_list($name = 'timeZoneList', $selected = 'Europe/Moscow'){
  $timezones = $this->get_array();
  $content = '<select size="1" name="' . $name . '" id="' . $name . '">' . "\n";
  foreach($timezones as $key => $value)
    $content .= '<option value="' . $value['offset'] . '" id="tz_' . $key . '"' . ((is_numeric($selected) ? $value['offset'] : $key) == explode(' ', $selected)[0] ? ' selected' : '') . '>' . $value['timezone'] . "\n";

  $content .= '</select>';
  return $content;
}
}

$tList = new TimeZoneList();
$tZones = $tList->get_array();
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=s, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<style>
    * {
     box-sizing: border-box;
   }
   .decor {
    position: relative;
    max-width: 600px;
    margin: 0px auto 0px;
    border-radius: 30px;
    background-color: #f7f7f7;
    margin-bottom: 20px;
    margin-top: 20px;
  }
  .form-left-decoration, .form-right-decoration {
   content: "";
   position: absolute;
   width: 50px;
   height: 20px;
   background: #008337;
   border-radius: 20px;
 }
 .form-left-decoration {
   bottom: 60px;
   left: -30px;
 }
 .form-right-decoration {
   top: 60px;
   right: -30px;
 }
 .form-left-decoration:before, .form-left-decoration:after, .form-right-decoration:before, .form-right-decoration:after {
   content: "";
   position: absolute;
   width: 50px;
   height: 20px;
   border-radius: 30px;
   background: white;
 }
 .form-left-decoration:before {
   top: -20px;
 }
 .form-left-decoration:after {
   top: 20px;
   left: 10px;
 }
 .form-right-decoration:before {
   top: -20px;
   right: 0;
 }
 .form-right-decoration:after {
   top: 20px;
   right: 10px;
 }
 .circle {
   position: absolute;
   bottom: 80px;
   left: -55px;
   width: 20px;
   height: 20px;
   border-radius: 50%;
   background: white;
 }
 .form-inner {
   padding: 50px;
 }
 .form-inner input, .form-inner textarea, .form-inner select {
   display: block;
   width: 100%;
   padding: 0 20px;
   margin-bottom: 10px;
   background: #E9EFF6;
   line-height: 40px;
   border-width: 0;
   border-radius: 20px;
   font-family: 'Roboto', sans-serif;
   margin: 8px;
 }
 .form-inner select {
  padding: 12px;
  border-radius: 5px;
}
.form-inner input[type="submit"] {
 margin-top: 30px;
 background: #008337;
 border-bottom: 4px solid #008000;
 color: white;
 font-size: 14px;
}
.form-inner textarea[name="text"] {
 resize: none;
}
.form-inner h3 {
 margin-top: 0;
 font-family: 'Roboto', sans-serif;
 font-weight: 500;
 font-size: 24px;
 color: #707981;
}

textarea.phone {
  line-height: 24px;
  padding: 10px;
}
.contacts_panel {
  display: flex;
  align-items: center;
  padding: 0 45px;
}

.contacts_panel input {
  line-height: 25px;
  border-radius: 10px;
}

.contacts_panel #save {
  cursor: pointer;
}
</style>
<?
$sql = "SELECT * FROM `phone` WHERE user = '$user'";
$data = $xpdo->query($sql);
$list = [];
foreach($data->fetchAll() as $val)
  $list[$val['list']][$val['id']] = ['phone' => $val['phone'], 'contact' => $val['contact']];
?>
<script>
  var list = <?=json_encode($list)?>;
</script>

<form class="decor" action="http://78.47.124.109/assets/test/index.php" method="post">
  <div class="form-left-decoration"></div>
  <div class="form-right-decoration"></div>
  <div class="circle"></div>
  <div class="form-inner">
    <?if(isset($edit_row)):?>
      <input type="hidden" name="id" value="<?=$edit_row['id']?>">
    <?endif?>

    <b>Номера получателей</b>
    <textarea placeholder="Список номеров (каждый с новой строки)" name="phone" class="phone"><?
      if(isset($edit_row)){
        $edit_row['user_phone'] = array_map('trim', explode(',', $edit_row['user_phone']));
        echo implode(PHP_EOL, $edit_row['user_phone']);
      }
      ?>
    </textarea>
    <div class="contacts_panel">
      <input type="text" id="new_list" placeholder="Название списка">
      <div id="save">Сохранить</div>
    </div>
    <b>Контакты</b>
    <select style="padding: 12px;border-radius: 5px;" name="se_phone" id="" class="se_phone" onchange="Phone(this)">
      <option value="">Выберите список</option>
      <?foreach($list as $cat => $contacts):?>
      <option value="<?=$cat?>"><?=$cat?></option>
      <?endforeach?>
    </select>
    <b>Номер отправителя</b>
    <input type="text" placeholder="От Кого" name="sender_phone" class="phones" value="<?=isset($edit_row) ? $edit_row['se_phone'] : ''?>">
    <b>Временная зона</b>
    <?=$tList->get_html_list('tz', isset($edit_row) ? $edit_row['tz_name'] : 'Europe/Moscow')?>
    <input type="hidden" name="tz_name" value="<?=isset($edit_row) ? $edit_row['tz_name'] : 'Europe/Moscow'?>">
    <b>Дата активации</b>
    <input type="date" placeholder="Дата" name="date" value="<?=isset($edit_row) ? $date_from['date'] : ''?>">
    <b>Время активации</b>
    <input type="time" placeholder="Время" name="time" value="<?=isset($edit_row) ? $date_from['time'] : ''?>">
    <b>Количество сообщений в секунду</b>
    <input type="text" placeholder="Рекомендуемое количество 1-10 смс в секунду" onchange="handleChange(this);" name="limit_sec" value="<?=isset($edit_row) ? $edit_row['limit_sec'] : ''?>">
    <input type="hidden" name="user" value="<?=isset($edit_row) ? $edit_row['user'] : $user?>">
<b>Сообщение</b>
    <textarea placeholder="Ваше сообщение..." rows="5" name="text"><?=isset($edit_row) ? $edit_row['massage'] : ''?></textarea>
    <input type="submit" name="sbt">
  </div>
</form>
<script>
  $('[name="tz"]').change(function(){
    $('[name="tz_name"]').val($('[name="tz"] option:selected').text());
  });

  function Phone(e){
   let phone = document.querySelector('.phone');
   var phones = '';

   $('#new_list').val(e.value);
   if(typeof list[e.value] != 'undefined')
     $.each(list[e.value], function(idx, val){
       phones += val.phone + "\r\n";
     });

   phone.value = phones;
 }
 $('.contacts_panel #save').click(function(){
  var user = $('[name="user"]').val();
  var list_name = $('#new_list').val();
  var contacts = $('.phone').val();
  if(!list_name){
    $('#new_list').focus()
    return false;
  }

  if(!contacts){
    $('.phone').focus()
    return false;
  }
  $.ajax({
    type: "POST",
    url: "http://78.47.124.109/assets/test/index.php",
    data: {mode: 'list_save', user: user, list_name: list_name, contacts: contacts}
  }).done(function(msg){
    alert(msg);
  });
});
</script>
</body>
</html>
<?php