<?php
/* MT4Analysis - Change Closed trade magic or comment.
   Copyright (C) 2010, 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. Mar/2010, Rick Smereka */

// initialize session
session_start();

require '../lib/constants.php';
require '../lib/parse.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;
$_SESSION['rpath_2_root'] = '..';

function set_dd_vars()
{
   // Populate drop-down session variables based on item changed.
   /* 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 <= 4; $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'] = $_GET['dd1'];
               $_SESSION['dname'] = $_SESSION['dd1'];
               $_SESSION['dd2'] = $_SESSION['account'] = DD_NULL;
               $_SESSION['dd3'] = $_SESSION['cp'] = DD_NULL;
               $_SESSION['dd4'] = $_SESSION['ticket'] = DD_NULL;
               break;

            case 2:
               // account changed
               $_SESSION['dd2'] = $_GET['dd2'];
               $_SESSION['account'] = $_SESSION['dd2'];
               $_SESSION['dd3'] = $_SESSION['cp'] = DD_NULL;
               $_SESSION['dd4'] = $_SESSION['ticket'] = DD_NULL;
               break;

            case 3:
               // currency pair changed
               $_SESSION['dd3'] = $_GET['dd3'];
               $_SESSION['cp'] = $_SESSION['dd3'];
               $_SESSION['dd4'] = $_SESSION['ticket'] = DD_NULL;
               break;

            case 4:
               // ticket changed
               $_SESSION['dd4'] = $_GET['dd4'];
               $_SESSION['ticket'] = $_SESSION['dd4'];
               break;
            }
         }
      }

   /* print_r($_GET);
   print_r($_SESSION); */
}

// if form has not been submitted, display it
if (!isset($_POST['submit']))
   {
$title = 'Change Closed Trade Magic/Comment';
?>
<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
/* some Php versions still have 'magic quotes' turned on and since
   I cannot turn this off at runtime, the following code removes
   the quotes from the I/O arrays, taken from
   http://php.net/manual/en/security.magicquotes.disabling.php */
if (get_magic_quotes_gpc())
   {
   function stripslashes_deep($value)
      {
         $value = is_array($value) ?  array_map('stripslashes_deep', $value) :
                                      stripslashes($value);
         return $value;
      }

   $_POST = array_map('stripslashes_deep', $_POST);
   $_GET = array_map('stripslashes_deep', $_GET);
   $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
   $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
   }

page_header($title);
set_dd_vars();
puts("<TABLE BORDER='2' ALIGN='CENTER'>");
puts("<FORM NAME='com' 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++;
   }
?>
</SELECT>
</TD>
</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();
      }
   }
?>
</SELECT>
</TD>
</TR>
<TR>
<TH>Currency Pair</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 currency pair dropdown if there is a valid account
if (isset($_SESSION['dd2']) && $_SESSION['dd2'] != DD_NULL)
   {
   $query = 'SELECT DISTINCT currencyPair AS id FROM closedtrade WHERE ';
   $query .= "account = '{$_SESSION['dd2']}'";
 
   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(currency pairs), SQL syntax error?');

      if ($stmt->execute())
         {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
            // record with a zero pair is not a trade
            if ($row['id'] == '0')
               continue;

            $mes = "<OPTION VALUE='{$row['id']}'";

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

            $query = 'SELECT description FROM currencyPair WHERE id = ';
            $query .= $row['id'];
            $desc = db_get_one($dbh, $query, 'description');

            if ($desc == '')
               $desc = 'Unknown';

            $mes .= ">$desc</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd2 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }
?>
</SELECT>
</TD>
</TR>
<TR>
<TH>Ticket</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 ticket dropdown if there is a valid currency pair
if (isset($_SESSION['dd3']) && $_SESSION['dd3'] != DD_NULL)
   {
   $query = 'SELECT ticket, opendatime, closedatime FROM closedtrade WHERE ';
   $query .= "account = '{$_SESSION['dd2']}' AND currencyPair = ";
   $query .= $_SESSION['dd3'] . ' ORDER BY ticket';
 
   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(currency pairs), SQL syntax error?');

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

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

            $mes .= ">{$row['ticket']}:{$row['opendatime']}-";
            $mes .= "{$row['closedatime']}</OPTION>";
            puts($mes);
            }
         }
      else
         die('Unable to locate dd2 data');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }
?>
</SELECT>
</TD>
</TR>
<?php
// only enable magic and comment 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;

if ($state)
   {
   $query = 'SELECT magic, comment FROM closedtrade WHERE ticket = ';
   $query .= $_SESSION['dd4'];

   try
      {
      if (!$stmt = $dbh->prepare($query))
         die('PDO prepare failed(currency pairs), SQL syntax error?');

      if ($stmt->execute())
         $row = $stmt->fetch(PDO::FETCH_ASSOC);
      else
         die("PDO execute failed ticket {$_SESSION['dd4']}");
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }

   $magic = $row['magic'];
   $comment = $row['comment'];
   puts('<TR>');
   puts('<TH>Magic</TH>');
   puts("<TD><INPUT TYPE='TEXT' SIZE='60' NAME='magic' VALUE='$magic'>");
   puts('</TR>');
   puts('<TR>');
   puts('<TH>Comment</TH>');
   puts("<TD><INPUT TYPE='TEXT' SIZE='60' NAME='comment' VALUE='$comment'>");
   puts('</TR>');
   }
?>
<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='Change'";

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

$mes .= '/>';
puts($mes);
?>
</TD>
</TR>
</FORM>
</TABLE>
<?php
   // end of form display before submission
   }
else
   {
   // form has been submitted, update database
   // make sure database is in rw mode
   db_mode(true);
   $db = mt4a_dbname();
   $com = 'UPDATE closedtrade SET magic = ';
   $com .= "'" . $_POST['magic'] . "', comment = ";
   $com .= "'" . $_POST['comment'] . "' WHERE ticket = ";
   $com .= $_SESSION['ticket'];

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

      if (!$stmt = $dbh->prepare($com))
         die('PDO prepare failed, SQL syntax error?');

      if (!$stmt->execute())
         die('PDO execute of database update failed');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }

   // refresh page
   $fname = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
   header("Location: http://$fname");
   exit;
   }

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


