<?php

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

include ('config_local.php');

if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {

  die('Не могу подключиться к БД');

}  

$db -> exec('SET CHARACTER SET utf8');

$selected = [];

if ($_REQUEST['action']=='submit') {

  foreach($_REQUEST as $key=>$value) {
  
    if (strpos($key,'unit_')===0) {

      $group_id=intval(substr($key,5));
      $unit_id=$value;
      setcookie('unit_'.$group_id,$unit_id,time()+86400*365*10);
      $selected[$group_id]=$unit_id;
      
    }

  }

?>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="refresh" content="2; url=index.php">
  <meta name="GENERATOR" content="Mozilla/4.72 [cp1251] (X11; U; Linux 2.2.12-20smp i686) [Netscape]">
  <title>WeatherMon (Настройки)</title>
  <link rel="icon" href="favicon.png" />
</head>
<body text="black" bgcolor="silver" link="blue" vlink="#000080" alink="#FF0000">
<h1 align="center">Сохранено...</h1>
</body>
<?php
  
} else {

  foreach($_COOKIE as $key=>$value) {
  
    if (strpos($key,'unit_')===0) {

      $group_id=intval(substr($key,5));
      $unit_id=$value;
      setcookie('unit_'.$group_id,$unit_id);
      $selected[$group_id]=$unit_id;
      
    }
  
  }

?>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="GENERATOR" content="Mozilla/4.72 [cp1251] (X11; U; Linux 2.2.12-20smp i686) [Netscape]">
  <title>WeatherMon (Настройки)</title>
  <link rel="icon" href="favicon.svg" />
</head>
<body text="black" bgcolor="silver" link="blue" vlink="#000080" alink="#FF0000">

<?php

  
$q = $db -> prepare(
  'select id,name,(select count(*) from units where unit_group=g.id) cnt from unit_groups g'
);
$q -> execute();
          
echo '<form action="setup.php" method="get">';
while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
  $group_id = $row['id'];
  $group_name = $row['name'];
  $group_cnt = $row['cnt'];
  
  echo '<h3 align="center">'.$group_name.'</h3>';

  $q_p = $db -> prepare(
    'select id,name from units where unit_group='.$group_id
  );
  
  $q_p->execute();

  echo '<center><select name="unit_'.$group_id.'" size='.$group_cnt.'>';  
  while ($row_p = $q_p -> fetch(PDO::FETCH_ASSOC)) {
  
    if ($selected[$group_id]==$row_p['id']) {
      echo '<option selected value="'.$row_p['id'].'">'.$row_p['name'].'</option>';
    } else {
      echo '<option value="'.$row_p['id'].'">'.$row_p['name'].'</option>';
    }  
  
  }
  echo '</select></center>';
}
echo '<input type="hidden" name="action" value="submit">';
echo '<p><center><input type="submit" value="Сохранить настройки"></center>';
echo '</form>';

}
             
?>
</body>
</html>