<?php
/* MT4Analysis - Manage Trading Databases.
   Copyright (C) 2009, Future Lab.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, get a copy via the Internet at
   http://gnu.org/copyleft/gpl.html or write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston,
   MA 02111-1307 USA

   You can contact the author via email at rsmereka@future-lab.com

   Original version. Jun/2009, Rick Smereka */

// initialize session
session_start();

require '../lib/constants.php';
require '../lib/mt4analysis.php';
require '../lib/db.php';

// no set value in drop-down constant
define('DD_NULL', '00');

// no set display in drop-down constant
define('DDD_NULL', '--Select--');

// html null drop-down value option line, not selected
$dd_null_ns = "<OPTION VALUE='" . DD_NULL . "'>" . DDD_NULL . '</OPTION>';

// html null drop-down value option line, selected
$dd_null_sel = "<OPTION VALUE='" . DD_NULL . "' SELECTED>" . DDD_NULL; 
$dd_null_sel .= '</OPTION>';

$database_driver = DATABASE_DRIVER;
$abort = ', program abort';
$_SESSION['rpath_2_root'] = '..';

function set_dd_vars()
{
   // Populate drop-down session variables based on item changed.
   global $database_driver, $abort;
   $mname = 'set_dd_vars';

   /* when any drop-down value is changed, the new value is passed as
      a 'GET' variable and the form is reloaded, all drop-down values
      are stored in session variables, any drop-down that has not been
      set has no corresponding session variable, 'GET' and 'SESSION'
      variable names are codes: 'dd' for dropdown 
      followed by the drop-down number, for example: 'dd1' is the
      database file name dropdown (the first one) and 'dd2' is the
      account name dropdown */

   for($i = 1; $i <= 6; $i++)
      {
      $idx = 'dd' . $i;

      // if 'GET' var is set, save it in a 'SESSION' var
      if (isset($_GET[$idx]) && strlen($_GET[$idx]) > 0)
         {
         $_SESSION[$idx] = $_GET[$idx];

         // populate session var logic
         switch($i)
            {
            case 1:
               // database changed
               $_SESSION['dd1'] = $_SESSION['dname'] = $_GET['dd1'];
               $_SESSION['dd2'] = $_SESSION['dd3'] = $_SESSION['dd4'] = 
                 $_SESSION['account'] = $_SESSION['broker'] =
                 $_SESSION['cpset'] = DD_NULL;
               break;

            case 2:
               /* account changed (attempt to find and load broker and
                  currency pair set) */
               $_SESSION['dd2'] = $_SESSION['account'] = $_GET['dd2'];
               $query = 'SELECT broker FROM account WHERE id = ';
               $query .= "'" . $_SESSION['dd2'] . "'";
               $db = mt4a_dbname();

               try
                  {
                  $dbh = new PDO("$database_driver:$db");

                  if (!$stmt = $dbh->prepare($query))
                     {
                     $mes = "$mname:PDO prepare failed(get broker id), ";
                     $mes .= 'SQL syntax error?' . $abort;
                     die($mes);
                     }

                  if ($stmt->execute())
                     $row = $stmt->fetch(PDO::FETCH_ASSOC);
                  else
                     die("$mame:PDO execute failed(get broker id)" . $abort);
                  }
               catch(PDOException $e)
                  {
                  print "Error!:" . $e->getMessage() . $abort . "\n";
                  die();
                  }

               if (!isset($row['broker']) || $row['broker'] <= 0)
                  {
                  $_SESSION['dd3'] = $_SESSION['dd4'] = 
                    $_SESSION['broker'] = $_SESSION['cpset'] = DD_NULL;
                  return;
                  }

               $_SESSION['dd3'] = $_SESSION['broker'] = $row['broker'];
               $query = 'SELECT currencyPairSet from broker WHERE id = ';
               $query .= "'" . $row['broker'] . "'";
               $cpset = db_get_one($dbh, $query, 'currencyPairSet');

               if ($cpset == '')
                  {
                  $_SESSION['dd4'] = $_SESSION['cpset'] = DD_NULL;
                  return;
                  }

               $_SESSION['dd4'] = $_SESSION['cpset'] = $cpset;
               break;

            case 3:
               /* broker changed (attempt to find and load currency pair
                  set) */
               $_SESSION['dd3'] = $_SESSION['broker'] = $_GET['dd3'];
               $query = 'SELECT currencyPairSet from broker WHERE id = ';
               $query .= "'" . $_SESSION['dd3'] . "'";
               $db = mt4a_dbname();

               try
                  {
                  $dbh = new PDO("$database_driver:$db");

                  if (!$stmt = $dbh->prepare($query))
                     {
                     $mes = "$mname:PDO prepare failed(get cp set id), ";
                     $mes .= 'SQL syntax error?' . $abort;
                     die($mes);
                     }

                  if ($stmt->execute())
                     $row = $stmt->fetch(PDO::FETCH_ASSOC);
                  else
                     die("$mame:PDO execute failed(get cp set id)" . $abort);
                  }
               catch(PDOException $e)
                  {
                  print "Error!:" . $e->getMessage() . $abort . "\n";
                  die();
                  }

               if (!isset($row['currencyPairSet']) || 
                    $row['currencyPairSet'] <= 0)
                  {
                  $_SESSION['dd4'] = $_SESSION['cpset'] = DD_NULL;
                  return;
                  }

               $_SESSION['dd4'] = $_SESSION['cpset'] = $row['currencyPairSet'];
               break;

            case 4:
               // currency pair set changed
               $_SESSION['dd4'] = $_SESSION['cpset'] = $_GET['dd4'];
               break;

            case 5:
               // currency pair changed
               $_SESSION['dd5'] = $_SESSION['cp'] = $_GET['dd5'];
               break;

            case 6:
               // ea changed
               $_SESSION['dd6'] = $_SESSION['ea'] = $_GET['dd6'];
               break;
            }
         }
      }

   $dbh = null;
}

$title = 'Manage Trading Databases';
?>
<HTML>
<HEAD>
<?php puts("<TITLE>Mt4Analysis - $title</TITLE>"); ?>
<SCRIPT language=Javascript>
function reload(opt, fname, idx)
{
   var val = opt[opt.selectedIndex].value;
   self.location = fname + '?' + idx + '=' + urlencode(val);
}
function urlencode(inputString)
{
   var encodedInputString=escape(inputString);
   encodedInputString = encodedInputString.replace("+", "%2B");
   encodedInputString = encodedInputString.replace("/", "%2F");        
   return encodedInputString;
}
</SCRIPT>
</HEAD>
<BODY>
<A NAME="top"></A>
<?php page_header($title); ?>
<P>
<?php
// if form has not been submitted, display it
if (!isset($_POST['submit']))
   {
set_dd_vars();
puts("<TABLE BORDER='2'>");
puts("<FORM NAME='db' ACTION='{$_SERVER['PHP_SELF']}' METHOD='POST'>");
puts('<TR>');
puts('<TH>Database File Name</TH>');
$mes = "<TD><SELECT NAME='dd1' onchange=\"reload(this.form.dd1.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd1')\">";
puts($mes);
$sel = (isset($_SESSION['dd1'])) ? $_SESSION['dd1'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// get a list of every file in the trade path
$spath = (IN_PRODUCTION) ? $_SERVER['DOCUMENT_ROOT_OLD'] : 
                           $_SERVER['DOCUMENT_ROOT'];
$dpath = (IN_PRODUCTION) ? TRADE_PATH_PRODUCTION : TRADE_PATH_LOCAL;
$db_path = $spath . $dpath;
//p("spath=$spath,dpath=$dpath,db_path=$db_path");
$db_files = scandir($db_path);
$cnt = 1;

// populate dropdown (skip current and parent dot references)
foreach ($db_files as $db_file)
   {
   if ($db_file == '.' || $db_file == '..')
      continue;

   $mes = "<OPTION VALUE='$db_file'";

   if ($db_file == $sel)
      $mes .= ' SELECTED';

   $mes .= ">$db_file</OPTION>";
   puts($mes);
   $cnt++;
   }

puts('</SELECT>');
puts('</TD>');
puts('</TR>');
?>
<TR>
<TH>Account Name</TH>
<?php
$mes = "<TD><SELECT NAME='dd2' onchange=\"reload(this.form.dd2.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd2')\">";
puts($mes);
$sel = (isset($_SESSION['dd2'])) ? $_SESSION['dd2'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// only populate account dropdown if there is a valid database
if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   // build database path and name
   $db = mt4a_dbname();
   $query = 'SELECT id, description FROM account';
 
   try
      {
      $dbh = new PDO("$database_driver:$db");

      if (!$stmt = $dbh->prepare($query))
         {
         puts('</SELECT></TD></TR>');
         $mes = '<P><CENTER>Unable to open database, is this an SQLite';
         $mes .= 'database?</CENTER></P>';
         puts($mes);
         die();
         }

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $mes = "<OPTION VALUE='{$row['id']}'";

            if ($row['id'] == $sel)
               $mes .= ' SELECTED';

            $mes .= ">{$row['description']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd2 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

puts('</SELECT>');
puts('</TD>');

if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   puts("<TD><A HREF='account.php'>Add</A>");

   if (isset($_SESSION['dd2']) && $_SESSION['dd2'] != DD_NULL)
      {
      puts("|<A HREF='account.php?c={$_SESSION['dd2']}'>Change</A>|");
      puts("|<A HREF='account.php?d={$_SESSION['dd2']}'>Delete</A>");
      }

   puts('</TD>');
   }
?>
</TR>
<TR>
<TH>Broker Name</TH>
<?php
$mes = "<TD><SELECT NAME='dd3' onchange=\"reload(this.form.dd3.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd3')\">";
puts($mes);
$sel = (isset($_SESSION['dd3'])) ? $_SESSION['dd3'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// only populate broker dropdown if there is a valid account
if (isset($_SESSION['dd2']) && $_SESSION['dd2'] != DD_NULL)
   {
   $query = 'SELECT id, description FROM broker';
 
   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(load dd3), SQL syntax error?');

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $mes = "<OPTION VALUE='{$row['id']}'";

            if ($row['id'] == $sel)
               $mes .= ' SELECTED';

            $mes .= ">{$row['description']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd3 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

puts('</SELECT>');
puts('</TD>');

if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   puts("<TD><A HREF='broker.php'>Add</A>");

   if (isset($_SESSION['dd3']) && $_SESSION['dd3'] != DD_NULL)
      {
      puts("|<A HREF='broker.php?c={$_SESSION['dd3']}'>Change</A>");
      puts("|<A HREF='broker.php?d={$_SESSION['dd3']}'>Delete</A>");
      }

   puts('</TD>');
   }
?>
</TR>
<TR>
<TH>Currency Pair Set Name</TH>
<?php
$mes = "<TD><SELECT NAME='dd4' onchange=\"reload(this.form.dd4.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd4')\">";
puts($mes);
$sel = (isset($_SESSION['dd4'])) ? $_SESSION['dd4'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// only populate currency pair set dropdown if there is a valid broker
if (isset($_SESSION['dd3']) && $_SESSION['dd3'] != DD_NULL)
   {
   $query = 'SELECT id, description FROM currencyPairSet';
 
   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(load dd4), SQL syntax error?');

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $mes = "<OPTION VALUE='{$row['id']}'";

            if ($row['id'] == $sel)
               $mes .= ' SELECTED';

            $mes .= ">{$row['description']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd4 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

puts('</SELECT>');
puts('</TD>');

if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   puts("<TD><A HREF='cpset.php'>Add</A>");

   if (isset($_SESSION['dd4']) && $_SESSION['dd4'] != DD_NULL)
      {
      puts("|<A HREF='cpset.php?c={$_SESSION['dd4']}'>Change</A>");
      puts("|<A HREF='cpset.php?d={$_SESSION['dd4']}'>Delete</A>");
      }

   puts('</TD>');
   }
?>
</TR>
<TR>
<TH>Currency Pair</TH>
<?php
$mes = "<TD><SELECT NAME='dd5' onchange=\"reload(this.form.dd5.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd5')\">";
puts($mes);
$sel = (isset($_SESSION['dd5'])) ? $_SESSION['dd5'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

/* only populate currency pair names dropdown if there is a valid
   currency pair set name */
if (isset($_SESSION['dd4']) && $_SESSION['dd4'] != DD_NULL)
   {
   $query = 'SELECT id, description FROM currencyPair WHERE setID = ';
   $query .= "'" . $_SESSION['dd4'] . "'";
 
   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(load dd5), SQL syntax error?');

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $mes = "<OPTION VALUE='{$row['id']}'";

            if ($row['id'] == $sel)
               $mes .= ' SELECTED';

            $mes .= ">{$row['description']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd5 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

puts('</SELECT>');
puts('</TD>');

if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL &&
    isset($_SESSION['dd4']) && $_SESSION['dd4'] != DD_NULL)
   {
   puts("<TD><A HREF='cp.php'>Add</A>");

   if (isset($_SESSION['dd5']) && $_SESSION['dd5'] != DD_NULL)
      {
      puts("|<A HREF='cp.php?c={$_SESSION['dd5']}'>Change</A>");
      puts("|<A HREF='cp.php?d={$_SESSION['dd5']}'>Delete</A>");
      }

   puts('</TD>');
   }
?>
</TR>
<TR>
<TH>Expert Advisor</TH>
<?php
$mes = "<TD><SELECT NAME='dd6' onchange=\"reload(this.form.dd6.options, ";
$mes .= "'{$_SERVER['PHP_SELF']}', 'dd6')\">";
puts($mes);
$sel = (isset($_SESSION['dd6'])) ? $_SESSION['dd6'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

// only populate ea dropdown if there is a valid database 
if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   $query = 'SELECT id, description, magic FROM ea';
 
   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(load dd6), SQL syntax error?');

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            $mes = "<OPTION VALUE='{$row['id']}'";

            if ($row['id'] == $sel)
               $mes .= ' SELECTED';

            $mes .= ">{$row['description']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd6 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

puts('</SELECT>');
puts('</TD>');

if (isset($_SESSION['dd1']) && $_SESSION['dd1'] != DD_NULL)
   {
   puts("<TD><A HREF='ea.php'>Add</A>");

   if (isset($_SESSION['dd6']) && $_SESSION['dd6'] != DD_NULL)
      {
      puts("|<A HREF='ea.php?c={$_SESSION['dd6']}'>Change</A>");
      puts("|<A HREF='eap.php?d={$_SESSION['dd6']}'>Delete</A>");
      }

   puts('</TD>');
   }
?>


<TR>
<TD>&nbsp;</TD>
<?php
// only enable submit button when all required values are present (dd1-4)
$state = true;

if (!isset($_SESSION['dd1']) || $_SESSION['dd1'] == '00')
   $state = false;

if ($state && (!isset($_SESSION['dd2']) || $_SESSION['dd2'] == '00'))
   $state = false;

if ($state && (!isset($_SESSION['dd3']) || $_SESSION['dd3'] == '00'))
   $state = false;

if ($state && (!isset($_SESSION['dd4']) || $_SESSION['dd4'] == '00'))
   $state = false;

$mes = "<TD><INPUT TYPE='SUBMIT' NAME='submit' VALUE='Save Configuration'";

if (!$state)
   $mes .= ' disabled ';

$mes .= '/>';
puts($mes);
?>
</TD>
</TR>
</FORM>
</TABLE>
</P>
<?php
   // end of form display before submission
   }
else
   {
   // form has been submitted, validate it
   $mes = '';

   // drop-downs one through four must be valid
   for($i = 1; $i <= 4; $i++)
      {
      $idx = 'dd' . $i;

      if (!isset($_SESSION[$idx]) || strlen($_SESSION[$idx]) <= 0)
         {
         $mes = "Drop-down value $idx is missing";
         break;
         }
      }

   if ($mes == '')
      {
      // form is clean
      // make sure database is in rw mode
      db_mode();

      // set final session vars
      $_SESSION['dname'] = $_SESSION['dd1'];
      $_SESSION['account'] = $_SESSION['dd2'];
      $_SESSION['broker'] = $_SESSION['dd3'];
      $_SESSION['cpset'] = $_SESSION['dd4'];
      $_SESSION['cp'] = $_SESSION['dd5'];
      $_SESSION['ea'] = $_SESSION['dd6'];

      // update database
      $mes = 'UPDATE account SET ';
      $mes .= "broker = '{$_SESSION['broker']}' WHERE id = ";
      $mes .= "'" . $_SESSION['account'] . "'";
      $db = mt4a_dbname();

      try
         {
         $dbh = new PDO("$database_driver:$db");

         if (!$stmt = $dbh->prepare($mes))
            {
            $mes = "$mname:PDO prepare failed(save broker in account table), ";
            $mes .= 'SQL syntax error?' . $abort;
            die($mes);
            }

         if (!$stmt->execute())
            die("$mame:PDO execute failed(save broker in account table)" . $abort);
         }
      catch(PDOException $e)
         {
         print "Error!:" . $e->getMessage() . $abort . "\n";
         die();
         }

      $mes = 'UPDATE broker SET ';
      $mes .= "currencyPairSet = '{$_SESSION['cpset']}' WHERE id = ";
      $mes .= "'" . $_SESSION['broker'] . "'";

      try
         {
         if (!$stmt = $dbh->prepare($mes))
            {
            $mes = "$mname:PDO prepare failed(save cpset in broker table), ";
            $mes .= 'SQL syntax error?' . $abort;
            die($mes);
            }

         if (!$stmt->execute())
            die("$mame:PDO execute failed(save cpset in broker table)" . $abort);
         }
      catch(PDOException $e)
         {
         print "Error!:" . $e->getMessage() . $abort . "\n";
         die();
         }

      puts('<P><CENTER>Configuration successfully saved.</CENTER></P>');
      }
   }

require '../misc/footer.php';
?>
</BODY>
</HTML>
