<?php
/* MT4Analysis - Add/Change/Delete Brokers.
   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/parse.php';
require '../lib/datime.php';
require '../lib/db.php';

// db must be set
if (!isset($_SESSION['dname']) || strlen($_SESSION['dname']) <= 0)
   die('database not set');

// change ID supplied?
if (isset($_GET['c']) && strlen($_GET['c']) > 0)
   $change_id = $_GET['c'];
else
   $change_id = '';

// change submit ID supplied?
if (isset($_GET['cs']) && strlen($_GET['cs']) > 0)
   $change_submit_id = $_GET['cs'];
else
   $change_submit_id = '';

// 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;
$db = mt4a_dbname();
$abort = ', program abort';
$_SESSION['rpath_2_root'] = '..';
$title = 'Add/Change/Delete Broker Records';

// open database
try
   {
   $dbh = new PDO("$database_driver:$db");
   }
catch(PDOException $e)
   {
   db_error($e->getMessage(), $db);
   die();
   }

// delete record
if (isset($_GET['d']) && strlen($_GET['d']) > 0)
   {
   // make sure database is in rw mode
   db_mode(true);

   $id = $_GET['d'];
   $mes = "DELETE from broker WHERE id = '$id'";

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

      if (!$stmt->execute())
         die('Delete of broker record failed.');
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

// on record change, load fields
if ($change_id != '')
   {
   $query = 'SELECT id, description, currencyPairSet, normTimeOffset, ';
   $query .= 'normTimeStartDate, normTimeStarTime, DSTimeOffset, ';
   $query .= 'DSTimeStartDate, DSTimeStarTime, fiveDecimals ';
   $query .= "FROM broker WHERE id = '$change_id'";

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

      if ($stmt->execute())
         $brow = $stmt->fetch(PDO::FETCH_ASSOC);
      }
   catch(PDOException $e)
      {
      db_error($e->getMessage(), $db);
      die();
      }
   }

// if form has not been submitted, display it
if (!isset($_POST['submit']))
   {
puts('<HTML>');
puts('<HEAD>');
puts("<TITLE>Mt4Analysis - $title</TITLE");
puts('</HEAD>');
puts('<BODY>');
puts("<A NAME='top'></A>");
page_header($title);
puts("<H2>Database: {$_SESSION['dname']}</H2>");

if (isset($_SESSION['broker']) && $_SESSION['broker'] != DD_NULL)
   {
   if (isset($brow['description']))
      $mes = $brow['description'];
   else
      {
      $query = 'SELECT description from broker where id = ';
      $query .= "'" . $_SESSION['broker'] . "'";
      $mes = db_get_one($dbh, $query, 'description');
      }
   }
else
   $mes = 'None';

puts("<H2>Broker: $mes</H2>");
puts("<P><TABLE BORDER='2'>");

// different form action depending on whether a change record is in effect
$mes = "<FORM NAME='account' ACTION='{$_SERVER['PHP_SELF']}";

if ($change_id != '')
   $mes .= "?cs=$change_id' ";
else
   $mes .= "' ";

$mes .= "METHOD='POST'>";
puts($mes);
puts('<TR>');
puts('<TH>Description</TH>');

if ($change_id != '')
   $desc = $brow['description'];
else
   $desc = '';

puts("<TD><INPUT TYPE='TEXT' SIZE='40' NAME='desc' VALUE='$desc'>");
?>
</TD>
</TR>
<TR>
<TH>Currency Pair Set</TH>
<?php
puts("<TD><SELECT NAME='cpset'>");
$sel = (isset($brow['currencyPairSet'])) ? $brow['currencyPairSet'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);
$query = 'SELECT id, description FROM currencyPairSet';
 
try
   {
   if (!$stmt = $dbh->prepare($query))
      die('PDO prepare failed(load brokers), 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 currency pair set data');
   }
catch(PDOException $e)
   {
   db_error($e->getMessage(), $db);
   die();
   }
?>
</SELECT>
</TD>
</TR>
<TR>
<TH>Normal Time(Non-DST) Offset</TH>
<?php
if ($change_id != '')
   $nto = $brow['normTimeOffset'];
else
   $nto = '';

puts("<TD><INPUT TYPE='TEXT' SIZE='2' MAXLENGTH='2' NAME='nto' VALUE='$nto'>");
puts('</TD>');
puts('</TR>');
puts('<TR>');
puts('<TH>Normal Time(Non-DST) Start Date</TH>');

if ($change_id != '')
   {
   $mm = substr($brow['normTimeStartDate'], 0, 2);
   $dd = substr($brow['normTimeStartDate'], 2, 2);
   }
else
   $mm = $dd = '';

$mes = "<TD>Month: <INPUT TYPE='TEXT' SIZE='2' MAXLENGTH='2' ";
$mes .= "NAME='ndm' VALUE='$mm'> Day: <INPUT TYPE='TEXT' SIZE='2' ";
$mes .= "MAXLENGTH='2' NAME='ndd' VALUE='$dd'>";
puts($mes);
puts('</TD>');
puts('</TR>');
puts('<TR>');
puts('<TH>Normal Time(Non-DST) Start Time</TH>');

if ($change_id != '')
   {
   $hh = substr($brow['normTimeStarTime'], 0, 2);
   $mm = substr($brow['normTimeStarTime'], 2, 2);
   }
else
   $hh = $mm = '';

$mes = "<TD>Hour: <INPUT TYPE='TEXT' SIZE='2' MAXLENGTH='2' ";
$mes .= "NAME='nth' VALUE='$hh'> Minute: <INPUT TYPE='TEXT' ";
$mes .= "SIZE='2' MAXLENGTH='2' NAME='ntm' VALUE='$mm'>";
puts($mes);
?>
</TD>
</TR>
<TR>
<TH>DST Time Offset</TH>
<?php
if ($change_id != '')
   // if DST offset is -1, treat as not present
   if ($brow['DSTimeOffset'] == -1)
      $dto = '';
   else
      $dto = $brow['DSTimeOffset'];
else
   $dto = '';

puts("<TD><INPUT TYPE='TEXT' SIZE='2' MAXLENGTH='2' NAME='dto' VALUE='$dto'>");
puts('</TD>');
puts('</TR>');
puts('<TR>');
puts('<TH>DST Time Start Date</TH>');

if ($change_id != '')
   {
   $mm = substr($brow['DSTimeStartDate'], 0, 2);
   $dd = substr($brow['DSTimeStartDate'], 2, 2);
   }
else
   $mm = $dd = '';

$mes = "<TD>Month: <INPUT TYPE='TEXT' SIZE='2' MAXLENGTH='2' ";
$mes .= "NAME='ddm' VALUE='$mm'> Day: <INPUT TYPE='TEXT' SIZE='2' ";
$mes .= "MAXLENGTH='2' NAME='ddd' VALUE='$dd'>";
puts($mes);
puts('</TD>');
puts('</TR>');
puts('<TR>');
puts('<TH>DST Time Start Time</TH>');

if ($change_id != '')
   {
   $hh = substr($brow['DSTimeStarTime'], 0, 2);
   $mm = substr($brow['DSTimeStarTime'], 2, 2);
   }
else
   $hh = $mm = '';

$mes = "<TD>Hour: <INPUT TYPE='TEXT' SIZE='2' MAXLENGTH='2' ";
$mes .= "NAME='dth' VALUE='$hh'> Minute: <INPUT TYPE='TEXT' ";
$mes .= "SIZE='2' MAXLENGTH='2' NAME='dtm' VALUE='$mm'>";
puts($mes);
?>
</TD>
</TR>
<TR>
<TH>Five Decimal Prices</TH>
<?php
puts("<TD><SELECT NAME='fivedecimals'>");
$sel = ($brow['fiveDecimals'] == '1') ? $brow['fiveDecimals'] : DD_NULL;
$mes = ($sel == DD_NULL) ? $dd_null_sel : $dd_null_ns;
puts($mes);

for($i = 0; $i <= 1; $i++)
   {
   $mes = "<OPTION VALUE='$i'";

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

   $mes .= '>';
   $mes .= ($i) ? 'Yes' : 'No';
   $mes .= '</OPTION>';
   puts($mes);
   }
?>
</SELECT>
</TD>
</TR>
<TR>
<TD>&nbsp;</TD>
<TD><INPUT TYPE='SUBMIT' NAME='submit' VALUE='Submit'>
</TD>
</TR>
</FORM>
</TABLE>
</P>
<!-- Javascript set focus on first form field -->
<SCRIPT LANGUAGE="Javascript">
document.account.desc.focus();
</SCRIPT>
<P>
<TABLE BORDER='2'>
<TR>
<TH>ID</TH>
<TH>Description</TH>
<TH>Action</TH>
</TR>
<?php
// display all records in another table
$query = 'SELECT id, description FROM broker ORDER BY id';

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

   if ($stmt->execute())
      {
      while($row = $stmt->fetch(PDO::FETCH_ASSOC))
         {
         puts('<TR>');
         tableputd($row[id], 'C');
         tableputd($row['description']);
         puts("<TD><A HREF='broker.php?c={$row['id']}'>Change</A> | ");
         puts("<A HREF='broker.php?d={$row['id']}'>Delete</A></TD>");
         puts('</TR>');
         }

      puts('</TABLE>');
      }
   else
      puts('</TABLE><P>No account records on file</P>');
   }
catch(PDOException $e)
   {
   db_error($e->getMessage(), $db);
   die();
   }

   puts('</P>');
   // end of form display before submission
   }
else
   {
   // form has been submitted, validate it
   $mes = '';
   $has_norm_date = $has_norm_time = $has_nto = false;
   $has_dst_date = $has_dst_time = false;
 
   // description must be present
   if (!isset($_POST['desc']) || strlen($_POST['desc']) <= 0)
      $mes = 'Description must be present';

   // currency pair set must be present
   if ($mes == '' && (!isset($_POST['cpset']) || 
       strlen($_POST['cpset']) <= 0 || $_POST['cpset'] == DD_NULL))
      $mes = 'Currency pair set must be present';

   // normal time offset must be present and a number
   if ($mes == '' && (!isset($_POST['nto']) || strlen($_POST['nto']) <= 0 ||
       !num($_POST['nto'])))
      $mes = 'Normal time offset must be present and be a whole number';
    
   /* if normal time start date is present, both parts must be integers,
      optional, no DST if normal date and time not present */
   if ($mes == '' && (isset($_POST['ndm']) && strlen($_POST['ndm']) > 0))
      {
      if (!isset($_POST['ndd']) || !strlen($_POST['ndd']))
         $mes = 'Both month and day in mormal time start date must be present';

      if ($mes == '' && !num($_POST['ndm']))
         $mes = 'Normal time start date(month) must be a positive integer';

      if ($mes == '' && ($_POST['ndm'] < 1 || $_POST['ndm'] > 12))
         $mes = 'Normal time start date(month) must be between 1 and 12';

      if ($mes == '' && !num($_POST['ndd']))
         $mes = 'Normal time start date(day) must be a positive integer';

      if ($mes == '' && $_POST['ndd'] < 1)
         $mes = 'Normal time start date(day) must be a positive integer';

      if ($mes == '')
         {
         $year = date('Y');
         $d_in_month = days_in_month($year, $_POST['ndm']);
       
         if ($_POST['ndd'] > $d_in_month)
            {
            $mes = 'Normal time start date(day) must be between ';
            $mes .= 'one and ' . $d_in_month;
            }
         }

      $has_norm_date = true;
      }

   /* if normal time start time is present, both parts must be integers and
      in range, mandatory if normal time start date is present */
   if ($mes == '' && (isset($_POST['nth']) && strlen($_POST['nth']) > 0))
      {
      if (!isset($_POST['ntm']) || !strlen($_POST['ntm']))
         $mes = 'Both hour and minute in mormal time start time must be present';

      if ($mes == '' && !num($_POST['nth']))
         $mes = 'Normal time start time(hour) must be a positive integer';

      if ($mes == '' && ($_POST['nth'] < 0 || $_POST['nth'] > 23))
         $mes = 'Normal time start time(hour) must be between 0 and 23';

      if ($mes == '' && !num($_POST['ntm']))
         $mes = 'Normal time start time(minute) must be a positive integer';

      if ($mes == '' && $_POST['ntm'] < 0)
         $mes = 'Normal time start time(minute) must in rhw';

      if ($mes == '' && ($_POST['ntm'] < 0 || $_POST['ntm'] > 59))
         $mes = 'Normal time start time(minute) must be in the range 1 to 59';

      $has_norm_time = true;
      }

   /* if normal time start date is present, normal time start time must
      also be present */
   if ($mes == '' && $has_norm_date && !$has_norm_time)
      {
      $mes = 'Both normal time start date and normal time start time must ';
      $mes .= 'be present.';
      }

   /* if normal time start time is present, normal time start date must
      also be present */
   if ($mes == '' && $has_norm_time && !$has_norm_date)
      {
      $mes = 'Both normal time start date and normal time start time must ';
      $mes .= 'be present.';
      }

   /* DST time offset must be present if normal time start date is present
      and it must be a number */
   if ($mes == '' && isset($_POST['dto']) && strlen($_POST['dto']) > 0)
      {
      if ($_POST['dto'] == DD_NULL || !num($_POST['dto']))
         $mes = 'DST time offset must be a number';

      $has_nto = true;
      }

   if ($has_norm_date && !$has_nto)
      {
      $mes = 'DST time offset must be present when normal time start ';
      $mes .= 'date is present.';
      }

   if (!$has_norm_date && $has_nto)
      {
      $mes = 'DST Time offset cannot be present when normal time start ';
      $mes .= 'date is not present.';
      }

   /* if DST time start date is present, both parts must be integers,
      mandatory if normal time start date is present */
   if ($mes == '' && (isset($_POST['ddm']) && strlen($_POST['ddm']) > 0))
      {
      if (!isset($_POST['ddd']) || !strlen($_POST['ddd']))
         $mes = 'Both month and day in DST time start date must be present';

      if ($mes == '' && !num($_POST['ddm']))
         $mes = 'DST time start date(month) must be a positive integer';

      if ($mes == '' && ($_POST['ddm'] < 1 || $_POST['ddm'] > 12))
         $mes = 'DST time start date(month) must be between 1 and 12';

      if ($mes == '' && !num($_POST['ddd']))
         $mes = 'DST time start date(day) must be a positive integer';

      if ($mes == '' && $_POST['ddd'] < 1)
         $mes = 'DST time start date(day) must be a positive integer';

      if ($mes == '')
         {
         $year = date('Y');
         $d_in_month = days_in_month($year, (int)$_POST['ddm']);
       
         if ($_POST['ddd'] > $d_in_month)
            {
            $mes = 'DST time start date(day) must be between ';
            $mes .= 'one and ' . $d_in_month . '<BR />';
            $mes .= "year=$year,ddd={$_POST['ddd']},";
            $mes .= "ddm={$_POST['ddm']},d_in_month=$d_in_month<BR />";
            }
         }

      $has_dst_date = true;
      }

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

      // if broker is not using daylight saving time
      if (!$has_norm_date)
         {
         // set dates and times to empty string and set DST offset to -1
         $normTimeStartDate = $normTimeStarTime = $DSTimeStartDate =
                              $DSTimeStarTime = '';
         $dto = -1;
         }
      else
         {
         // make sure dates and times are already two digits
         $normTimeStartDate = lpad($_POST['ndm'], '0', 2) . 
                              lpad($_POST['ndd'], '0', 2);
         $normTimeStarTime = lpad($_POST['nth'], '0', 2) .
                             lpad($_POST['ntm'], '0', 2);
         $DSTimeStartDate = lpad($_POST['ddm'], '0', 2) .
                            lpad($_POST['ddd'], '0', 2);
         $DSTimeStarTime = lpad($_POST['dth'], '0', 2) .
                           lpad($_POST['dtm'], '0', 2);
         $dto = $_POST['dto'];
         }

      if ($change_submit_id == '')
         {
         // insert new broker record
         $mes = 'INSERT INTO broker (id, description, currencyPairSet, ';
         $mes .= 'normTimeOffset, normTimeStartDate, normTimeStarTime, ';
         $mes .= 'DSTimeOffset, DSTimeStartDate, DSTimeStarTime, fiveDecimals)';
         $mes .= ' VALUES(NULL, ';
         $mes .= sql_addquotes($_POST['desc'], true);
         $mes .= $_POST['cpset'] . ', ';
         $mes .= $_POST['nto'] . ', ';
         $mes .= sql_addquotes($normTimeStartDate, true);
         $mes .= sql_addquotes($normTimeStarTime, true);
         $mes .= $dto . ', ';
         $mes .= sql_addquotes($DSTimeStartDate, true);
         $mes .= sql_addquotes($DSTimeStarTime, true);
         $mes .= $_POST['fivedecimals'] . ')';
         }
      else
         {
         // modify broker record
         $mes = 'UPDATE broker SET ';
         $mes .= 'description = ' . sql_addquotes($_POST['desc'], true);
         $mes .= 'currencyPairSet = ' . $_POST['cpset'] . ', ';
         $mes .= 'normTimeOffset = ' . $_POST['nto'] . ', ';
         $mes .= 'normTimeStartDate = ' . 
                 sql_addquotes($normTimeStartDate, true);
         $mes .= 'normTimeStarTime = ' . sql_addquotes($normTimeStarTime, true);
         $mes .= 'DSTimeOffset = ' . $dto . ', ';
         $mes .= 'DSTimeStartDate = ' . sql_addquotes($DSTimeStartDate, true);
         $mes .= 'DSTimeStarTime = ' . sql_addquotes($DSTimeStarTime, true);
         $mes .= 'fiveDecimals = ' . $_POST['fivedecimals'] . ' ';
         $mes .= "WHERE id = '{$change_submit_id}'";
         }

      // puts("<P>mes=$mes</P></BODY><HTML>");

      try
         {
         if (!$stmt = $dbh->prepare($mes))
            die('PDO prepare failed(save broker), SQL syntax error?');

         if (!$stmt->execute())
            die('broker record save failed');
         }
      catch(PDOException $e)
         {
         db_error($e->getMessage(), $db);
         die();
         }

      $fname = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
      header("Location: http://$fname");
      exit;
      }
   else
      {
      // validation error, display error and ask user to try again
      puts('<HTML>');
      puts('<HEAD>');
      puts("<TITLE>Mt4Analysis - $title</TITLE>");
      puts('</HEAD>');
      puts('<BODY>');
      p("<CENTER>$mes</CENTER>");
      /* puts("post broker='{$_POST['br']}'");
      print_r($_POST); */
      p("<CENTER><A HREF='{$_SERVER['PHP_SELF']}'>Try Again</A></CENTER>");
      }
   }

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