<?php
   class MyDB extends SQLite3 {
      function __construct() {
         $this->open('/kirac/db/sungateway.db');
      }
   }

   $db = new MyDB();
   if(!$db) {
      echo $db->lastErrorMsg();
   }

   $db->exec("PRAGMA synchronous = OFF");

   $stationid = $_POST['fstationid']; //new device station id
   $deviceid = $_POST['fdeviceid'];   //new device id
   $recordno = $_POST['frecordno'];   //device record no to be copied.

   //get source modbus device
   $sql =<<<EOF
   SELECT * FROM tblmbusdevices WHERE kno=$recordno;
EOF;
   $ret = $db->query($sql);
   $row = $ret->fetchArray(SQLITE3_ASSOC);
   $devicedef = $row['device_def'];
   $commtype = $row['comm_type'];
   $swapmode = $row['swap_mode'];
   $deviceip = $row['device_ip'];
   $tcpport = $row['tcp_port'];
   $active = $row['active'];

   //insert new modbus device
   $sql =<<<EOF
   INSERT INTO tblmbusdevices (station_id, device_id, device_def,comm_type,swap_mode,device_ip,tcp_port,active)
   VALUES ('$stationid', $deviceid, '$devicedef',$commtype,$swapmode,'$deviceip',$tcpport,$active);
EOF;
   $db->exec($sql);

   //get new mbus device kno
   $sql =<<<EOF
   SELECT MAX(kno) as kno FROM tblmbusdevices;
EOF;
   $ret = $db->query($sql);
   $row = $ret->fetchArray(SQLITE3_ASSOC);
   $new_recordno = $row['kno'];

   //close db (for prevent getting db locked error)
   $db->close();
   unset($db);

   //reopen db
   $db = new MyDB();
   if(!$db) {
      echo $db->lastErrorMsg();
   }
   $db->exec("PRAGMA synchronous = OFF");

   //delete tblmbusvars_copy table first
   $sql =<<<EOF
   DROP TABLE tblmbusvars_copy;
EOF;
   $db->exec($sql);

   //copy mbus vars into new table
   $sql =<<<EOF
   CREATE TABLE tblmbusvars_copy AS SELECT * FROM tblmbusvars WHERE dkno=$recordno;
EOF;
   $db->exec($sql);

   //update mbus vars with new new_recordno
   $sql =<<<EOF
   UPDATE tblmbusvars_copy SET dkno = $new_recordno;
EOF;
   $db->exec($sql);

   //insert new data to mbus VarnishStat
   $sql =<<<EOF
   INSERT INTO tblmbusvars (dkno,reg_addr,mbus_function,swap_mode,reg_var_type,reg_multiplier,reg_def) SELECT dkno,reg_addr,mbus_function,swap_mode,reg_var_type,reg_multiplier,reg_def FROM tblmbusvars_copy;
EOF;
   $db->exec($sql);

   $db->close();
?>
