<?php

function pg_createIndexes($tablename) {
 global $globalsettings;
 $sql="create index if not exists ".$tablename."_idx_mime_type on ".$tablename."(mime_type);
       create index if not exists ".$tablename."_idx_duration  on ".$tablename."(duration);
       create index if not exists ".$tablename."_idx_width     on ".$tablename."(width);
       create index if not exists ".$tablename."_idx_height    on ".$tablename."(height);
       create index if not exists ".$tablename."_idx_size      on ".$tablename."(size);
       create index if not exists ".$tablename."_idx_filedate  on ".$tablename."(filedate);
       create index if not exists ".$tablename."_idx_filename  on ".$tablename."(filename);
       create index if not exists ".$tablename."_idx_type      on ".$tablename."(type);
	   create index if not exists ".$tablename."_idx_topicname on ".$tablename."(topicname);";
 pg_query($globalsettings["db"]["pg_conn"], $sql);
} // function end

function createIndexes() {
 global $globalsettings;
 $sql="select tablename from pg_tables where tablename like 'chan_%'";
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
 if ($numrows != 0) {
  while ($row = pg_fetch_array($result)) {
   pg_createIndexes($row["tablename"]);
  } // if ($numrows != 0) 
 } // while ($row = pg_fetch_array
} // function end

function alterTables() {
 global $globalsettings;
 $sql="alter table forwardqueue add column if not exists tochanname text default 'default value';";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
  
 $sql="alter table repostmsg add column if not exists channelname text default 'default value';";
  pg_query($globalsettings["db"]["pg_conn"], $sql); 
  
 $sql="alter table repostmsg add column if not exists lastrun text default 'default value';";
  pg_query($globalsettings["db"]["pg_conn"], $sql); 
  
 $sql="alter table repostmsg add column if not exists nextrun text default 'default value';";
  pg_query($globalsettings["db"]["pg_conn"], $sql); 
  
 
} // function end


function pg_channelTableTemplate($tablename) {
$tabletemplate="create table if not exists ".$tablename." (
                 msgid          bigint not null,
                 link           text   not null,
                 grouped_id     bigint not null,
                 type           text   not null,
                 message        text   not null,
                 cleanmessage   text   not null,
                 reply_to       bigint not null,
                 msgdate        bigint not null,
                 mime_type      text   not null,
                 duration       bigint not null,
                 width          bigint not null,
                 height         bigint not null,
                 size           bigint not null,
                 filedate       bigint not null,
                 filename       text   not null,
                 user_id        bigint not null,
                 username       text   not null,
                 first_name     text   not null,
                 last_name      text   not null,
                 bot            bigint not null,
                 chanid         bigint not null,
                 title          text   not null,
                 cleantitle     text   not null,
                 topic_id       bigint not null,
                 topicname      text   not null,
                 cleantopicname text   not null,
                  constraint ".$tablename."_pkey primary key(msgid));";
 return $tabletemplate;
} // funcion end

function createTables() {
 global $globalsettings;
 $sql="create table if not exists deletemessages(
        channelid         bigint not null,
        msgid             bigint not null,
        timestamp         bigint not null,
		 constraint deletemessages_pkey primary key(channelid, msgid))";
 pg_query($globalsettings["db"]["pg_conn"], $sql);

 $sql="create table if not exists repostmsg(
        channelid         text not null,
        lastruntime       bigint not null,
		 constraint repostmsg_pkey primary key(channelid))";
 pg_query($globalsettings["db"]["pg_conn"], $sql);
  
 $sql="create table if not exists requests(
        channelid         bigint not null,
		channelname       text   not null,
        msgid             bigint not null, 
        fulfillsmsgid     bigint not null default -1,
        fulfillsuserid    bigint not null default -1,
        fulfillsusername  text   not null default '-1',
        userid            bigint not null,
        username          text   not null,
        timestamp         bigint not null,
        fulfillstimestamp bigint not null default -1,
        request           text   not null,
        fulfillsmessage   text   not null default '-1',
		title             text   not null,
        year              bigint not null,
        fulfills          bigint not null default -1, 
        fulfillslink      text   not null default '-1',
	    link              text   not null,
        deleted           bigint not null default -1,
        announced         bigint not null default -1 
 )";
 pg_query($globalsettings["db"]["pg_conn"], $sql);
  
 $sql="create table if not exists cacheasks(
        grpid    bigint not null,
        grpname  text   not null,
        msgid    bigint not null,
        fromid   bigint not null,
        fromuser text   not null,
        date     bigint not null,
        message  text   not null)";
 pg_query($globalsettings["db"]["pg_conn"], $sql);

 $sql="create table if not exists bckworker(
        grpid    bigint not null,
        grpname  text   not null,
        lastrun  bigint not null,
        runafter bigint not null,
         constraint bckworker_pkey primary key(grpid));";
 pg_query($globalsettings["db"]["pg_conn"], $sql);

 $sql="create table if not exists settings(
        variable   text not null,
        value      text not null,
         constraint settings_pkey primary key(variable));";
 pg_query($globalsettings["db"]["pg_conn"], $sql);


 $sql="insert into settings (variable, value) values ('".pg_escape_string($globalsettings["db"]["pg_conn"], "floodwait")."', '".pg_escape_string($globalsettings["db"]["pg_conn"], "123")."') on conflict (variable) do nothing;";
 pg_query($globalsettings["db"]["pg_conn"], $sql);

 $sql="insert into settings (variable, value) values ('".pg_escape_string($globalsettings["db"]["pg_conn"], "forwardstopmsg")."', '".pg_escape_string($globalsettings["db"]["pg_conn"], "123")."') on conflict (variable) do nothing;";
 pg_query($globalsettings["db"]["pg_conn"], $sql);

 $sql="insert into settings (variable, value) values ('".pg_escape_string($globalsettings["db"]["pg_conn"], "alltimeforwards")."', '".pg_escape_string($globalsettings["db"]["pg_conn"], "1")."') on conflict (variable) do nothing;";
 pg_query($globalsettings["db"]["pg_conn"], $sql);


 $sql="create table if not exists forwardqueue(
        id         bigserial,
        forwardkey text   not null,
        sourceid   text   not null,
        targetid   bigint not null,
        msgid      bigint not null,
        album      bigint not null,
        to_topic   bigint not null,
        message    text   not null, 
        cover      text   not null,   
        width      bigint not null,
        heigth     bigint not null,
        runtime    bigint not null,
        filedate   bigint not null,
        filesize   bigint not null);";
 pg_query($globalsettings["db"]["pg_conn"], $sql);

/* 
 new column forwardtimestamp is not null default -1 - index on forwardtimestamp ?!?
 new column modus is not null default -1 - -1 live 1 auto
 @fwdstepper 
 $sql="update forwardqueue set forwardtimestamp=".time()." where forwardkey='".pg_escape_string($pg_conn, $aparraykey)."'";
 

*/

 $sql="select * from forwardqueue limit 1;";
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
 $numrows=pg_num_rows($result);
 
 if ($numrows == 0) { // -- reset sequence when forwardqueue is empty. 
  $sql="alter sequence forwardqueue_id_seq restart with 1;";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
 }
} // function end 

function getSettings() {
 global $globalsettings, $interval, $floodwait, $forwardstopmsg, $alltimeforwards;

 $sql="select variable, value from settings";
 $result=pg_query($globalsettings["db"]["pg_conn"], $sql);

 $currenttime=time(); // substrg - (auf super billig) 

  $numrows=pg_num_rows($result);
  if ($numrows != 0) {
   while ($row = pg_fetch_array($result)) {
    switch($row["variable"]) {
      case "floodwait":   $interval["fwdStepper"]["lastruntime"]=$row["value"]; 
                          $floodwait=$row["value"]; 
      break;
	  case "forwardstopmsg": 
	   if (substr((int)$row["value"] - time(),0,1) == "-" ) { $forwardstopmsg=0; } else $forwardstopmsg=$row["value"];
      break;
      case "alltimeforwards": $alltimeforwards=$row["value"];
      break;
   } // switch($row["variable"]) 
  } // while ($row = pg_fetch_array($result)) 
 } // if ($numrows != 0) 
} // function end

function recoverforwardqueue($mode=-1) {
 global $globalsettings, $recoverqueue, $toForward;

 $toForward=array();

 if ($mode==1) { $recoverqueue="yes"; } //overwrite pandabot.conf setting... 

// check channels.conf to remove not configured entrys from queue! 
// after channels.conf load!

// select * from forwardqueue f order by sourceid, msgid, id desc - sort new first 
// select * from forwardqueue f order by msgid, id desc - 

// new columne @ forwardqueue -> mode -1=live, 1=autosync

 if ($recoverqueue=="yes") {
  $sql="select
        forwardkey, 
        sourceid,       
        targetid,         
        msgid,      
        album,      
        to_topic,   
        message,       
        cover,      
        width,     
        heigth,     
        runtime,    
        filedate,   
        filesize,
		tochanname
        from forwardqueue";
  $result=pg_query($globalsettings["db"]["pg_conn"], $sql);

  $numrows=pg_num_rows($result);
  if ($numrows != 0) {
   while ($row = pg_fetch_array($result)) {
   $toForward[$row["forwardkey"]]["from"]=    $row["sourceid"]; 
   $toForward[$row["forwardkey"]]["to"]=      $row["targetid"];
   $toForward[$row["forwardkey"]]["msgid"]=   $row["msgid"];
   $toForward[$row["forwardkey"]]["album"]=   $row["album"];
   $toForward[$row["forwardkey"]]["topic"]=   $row["to_topic"];
   $toForward[$row["forwardkey"]]["text"]=    $row["message"];
   $toForward[$row["forwardkey"]]["cover"]=   $row["cover"];
   $toForward[$row["forwardkey"]]["width"]=   $row["width"];
   $toForward[$row["forwardkey"]]["height"]=  $row["heigth"];
   $toForward[$row["forwardkey"]]["runtime"]= $row["runtime"];
   $toForward[$row["forwardkey"]]["filedate"]=$row["filedate"];
   $toForward[$row["forwardkey"]]["filesize"]=$row["filesize"];
   $toForward[$row["forwardkey"]]["tochanname"]=$row["tochanname"];
   } // while ($row = pg_fetch_array($result)) 
  } // if ($numrows != 0)
 } // if ($recoverqueue=="yes")

 if ($recoverqueue!="yes") {
  $sql="delete from forwardqueue";
  pg_query($globalsettings["db"]["pg_conn"], $sql);
 } // if ($recoverqueue!="yes") 
} // function end

function pg_opendb() {
 global $globalsettings; 

if ($globalsettings["db"]["dbpass"]!="") { 
  $conn_string="host=".$globalsettings["db"]["dbhost"]." port=".$globalsettings["db"]["dbport"]." dbname=".$globalsettings["db"]["dbname"]." user=".$globalsettings["db"]["dbuser"]." password=.".$globalsettings["db"]["dbpass"]; } else $conn_string="host=".$globalsettings["db"]["dbhost"]." port=".$globalsettings["db"]["dbport"]." dbname=".$globalsettings["db"]["dbname"]." user=".$globalsettings["db"]["dbuser"]; 
  
// $pg_conn=pg_connect($conn_string) or die('Could not connect: ' . pg_last_error());
 $globalsettings["db"]["pg_conn"]=pg_connect($conn_string) or die('Could not connect: ' . pg_last_error());

 pg_query($globalsettings["db"]["pg_conn"], "SET application_name = 'pandabot php'");

 createTables();
 createIndexes();
 alterTables();
 recoverforwardqueue();
 getSettings();

} // function end

pg_opendb();

// topic <-> reply bug in parseData fixen... :&