Česky
Kamil Dudka

Tiny programs (C, C++, C#, ...)

File detail

Name:Downloaddealer.php [Download]
Detected charset:ISO-8859-2 - [Download as UTF-8]
Location: tiny > IIS > proj
Size:28.8 KB
Last modification:2022-09-09 13:06

Source code

<?php
include_once ("engine/ui.php");
 
// Check user authorization to access this page
UserAuth::singleton()-> tryAccess("dealer");
 
// Load design
HtStyleLink::linkUserStyle();
$layout= new BasicLayout;
$canvas= HtBlock::factory ("div", $layout, "#pageContent");
StupidIe::patchIfNeeded();
 
// menu initialization
$page= @$_GET["page"];
/*new MenuDealer ($layout, $page);*/
switch ($page) {
  default:
  case 'routes':
    new MenuDealer ($layout, 'routes');
    pageRoutes();
    break;
  case 'cart':
    new MenuDealer ($layout, 'cart');
    pageCart();
    break;
  case 'orders':
    new MenuDealer ($layout, 'orders');
    pageOrders();
    break;
}
$layout-> draw();
// end of main()
 
function pageStatistics() {
}
 
function pageRoutes() {
  $layout= $GLOBALS['layout'];
  $canvas= $GLOBALS['canvas'];
  $szUser= UserAuth::singleton()-> getUser();
  $szHrefBase=  Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=routes';
 
  if (isset ($_GET['route'])) {
    routeDetail ($szHrefBase);
    return;
  }
 
  define('TITLE', 'Dostupné spoje');
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
  $menu= new Menu ('Jízdenky');
  $li= HtInline::factory ("li", $menu->getInnerList());
  HtInline::factory ("p", $li)-> addText("Vyberte si spoj, na který chcete objednat jízdenky.");
  $layout-> addToBegin($menu);
 
  // TODO: avoid negative number of available tickets
  $q= new DbQuery (
    "SELECT routes.route_id, UNIX_TIMESTAMP(route_date) AS route_date, UNIX_TIMESTAMP(route_date) AS route_time,".
    "route_from, route_to, duration, COUNT(DISTINCT tickets.seat_id)-COUNT(DISTINCT order_items.seat_id)-COUNT(DISTINCT cart.seat_id) AS free ".
    "FROM routes JOIN tickets USING (route_id) ".//LEFT JOIN order_items USING (route_id) ".
    "LEFT JOIN order_items ON routes.route_id=order_items.route_id ".
    "LEFT JOIN cart ON cart.user='$szUser' AND routes.route_id=cart.route_id ".
    "WHERE route_date>NOW()".
    "GROUP BY routes.route_id ".
    "HAVING free>0 ".             // TODO: check this
    "ORDER BY route_date"
    );
  define('ALIGN_RIGHT','text-align:right;');
  $resTable= new QueryResult ($canvas,
    Array ('č. spoje','Datum','Odjezd','Z','Do','Doba jízdy','Volných míst','Jízdenky'),
    Array (ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT, 5=>ALIGN_RIGHT, ALIGN_RIGHT)
    );
  for ($i=0; $i< $q->getNumRows(); $i++) {
    $row= $q->fetchArray();
    $szHrefDetail= $szHrefBase.'&amp;route='.$row['route_id'];
    $row['route_id']= '<a href="'.$szHrefDetail.'">'.$row['route_id'].'</a>';
    $row['route_date']= date ("j.n.Y", $row["route_date"]);
    $row['route_time']= date ("H:i", $row["route_time"]);
    $row['duration'].= ' min';
    $row []= '<a href="'.$szHrefDetail.'">zobrazit</a>';
    $resTable->addRow($row);
  }
}
 
function routeDetail ($szHrefBase) {
  $route= $_GET['route'];
  if (!ini_get ("magic_quotes_gpc")) {
    // Security..
    $route= addslashes($route);
  }
  $q= new DbQuery (
    "SELECT route_id, UNIX_TIMESTAMP(route_date) AS route_date, route_from, route_to, duration ".
    "FROM routes WHERE route_id='$route'"
    );
 if ($q->getNumRows() !=1) {
    // navigation error, possible attack
    Header ('Location: '.$szHrefBase);
    exit();
  }
 
  $szUser= UserAuth::singleton()-> getUser();
  $layout= $GLOBALS['layout'];
  $canvas= $GLOBALS['canvas'];
 
  define('TITLE', 'Jízdenky');
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h2', $canvas)-> addText('Detail spoje');
  $menu= new Menu (TITLE);
  $layout-> addToBegin($menu);
 
  $row= $q->fetchArray();
  $info= new SimpleInfoMulticol($canvas, 2);
  $info-> setStyle ('border:1px dashed gray;');
  $info-> addPair (0, 'Číslo spoje', $row['route_id']);
  $info-> addPair (0, 'Datum', date ('j.n.Y', $row['route_date']));
  $info-> addPair (0, 'Odjezd', date ('H:i', $row['route_date']));
  $info-> addPair (1, 'Z', $row['route_from']);
  $info-> addPair (1, 'Do', $row['route_to']);
  $info-> addPair (1, 'Doba jízdy', $row['duration'].' min');
 
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
  if (@$_GET['op']=='addToCart' && @$_POST['addToCart']=='true')
    addToCart ($route);
 
  $q= new DbQuery (
    "SELECT tickets.seat_id, price ".
    "FROM tickets ".
    "LEFT JOIN order_items ON tickets.route_id=order_items.route_id AND tickets.seat_id=order_items.seat_id ".
    "LEFT JOIN cart ON cart.user='$szUser' AND tickets.route_id=cart.route_id AND tickets.seat_id=cart.seat_id ".
    "WHERE tickets.route_id='$route' AND order_items.seat_id IS NULL AND cart.seat_id IS NULL ".
    "ORDER BY tickets.seat_id"
    );
  $numRows= $q->getNumRows();
  if ($numRows) {
    Page::singleton()-> addToHead($script= new HtJavaScript);
    IndentedBlock::factory (
      new JsFunction ('resetAll()', $script),
      'x= document.getElementById("ticketsForm");'."\n".
      'x.reset();'
      );
    $jsSelectAll= new JsFunction ('selectAll()', $script);
    IndentedBlock::factory (
      new JsFunction ('orderSelected()', $script),
      'x= document.getElementById("ticketsForm");'."\n".
      'x.submit();'
      );
    IndentedBlock::factory ($jsSelectAll, 'resetAll();');
    $form= HtBlock::factory ('form', $canvas, '#ticketsForm', Array(
      'method' => 'post',
      'action' => $szHrefBase.'&amp;route='.$route.'&amp;op=addToCart'
      ));
 
    $resTable= new QueryResultMulticol ($form,
      Array('Číslo sedadla','Cena','Objednat'),
      Array('text-align:right;','text-align:right','text-align:center;'),
      $numRows, 2
      );
    for ($i=0; $i< $numRows; $i++) {
      $rowArray= $q->fetchArray();
      $seat_id= 'seat'.$rowArray['seat_id'];
      $rowArray['price'].= '&nbsp;Kč';
      $rowArray []= '<input id="'.$seat_id.'" type="checkbox" name="'.$seat_id.'" value="true" />';
      IndentedBlock::factory ($jsSelectAll, 'x= document.getElementById("'.$seat_id.'"); x.click();');
      $resTable-> addRow($rowArray);
    }
    $div= HtBlock::factory ('div', $form, '.summarySubmit');
    HtSingle::factory ('input', $div, '', Array (
      'name'   => 'addToCart',
      'type'   => 'hidden',
      'value'  => 'true'
      ));
    /*HtSingle::factory ('input', $div, '', Array (
      'type'   => 'reset',
      'value'   => 'Zrušit označení'
      ));*/
    HtSingle::factory ('input', $div, '', Array (
      'type'   => 'submit',
      'value'  => 'Objednat označené'
        ));
    $menu-> addItem ('javascript:resetAll();', 'Zrušit označení');
    $menu-> addItem ('javascript:selectAll();', 'Označit všechny');
    $menu-> addItem ('javascript:orderSelected();', 'Objednat označené', 'font-weight:bold;');
  } else {
    HtInline::factory ('p', $canvas)-> addText('Je nám líto, spoj je již <b>vyprodaný</b>.');
  }
  $menu-> addItem (NULL, NULL);
  $menu-> addItem ($szHrefBase, 'Vybrat jiný spoj');
}
 
function addToCart($route) {
  $canvas= $GLOBALS['canvas'];
  $szUser= UserAuth::singleton()-> getUser();
  $q= new DbQuery (
    "SELECT tickets.seat_id, price ".
    "FROM tickets ".
    "LEFT JOIN order_items ON tickets.route_id=order_items.route_id AND tickets.seat_id=order_items.seat_id ".
    "WHERE tickets.route_id='$route' AND order_items.seat_id IS NULL ".
    "ORDER BY tickets.seat_id"
    );
  $order= Array();
  $total=0;
  for ($i=0; $i<$q->getNumRows(); $i++) {
    $row= $q->fetchArray();
    $seat= $row['seat_id'];
    if (@$_POST['seat'.$seat]=='true') {
      $order []= $seat;
      $total+= $row['price'];
    }
  }
  $orderItemsCount=0;
  foreach ($order as $currentSeat) {
    new DbQuery (
      "INSERT INTO cart SET ".
      "user='$szUser', ".
      "route_id='$route', ".
      "seat_id='$currentSeat', ".
      "ctime=NOW()"
      );
    $orderItemsCount++;
  }
  $status= HtInline::factory ('p', $canvas);
  if ($orderItemsCount) {
    $status->addText('Do ');
    HtInline::factory ('a', $status, '', Array('href'=>Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=cart'))-> addText('nákupního košíku');
    $status->addText(' bylo přidáno <b>'.$orderItemsCount.'</b> jízdenek za celkem <b>'.$total.'&nbsp;Kč</b>.');
  } else {
    $status->addText('<b>Pozor!</b> Nebyly objednány žádné jízdenky.');
  }
}
 
function pageCart() {
  $layout= $GLOBALS['layout'];
  $canvas= $GLOBALS['canvas'];
  $szHrefBase= Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=cart';
  $szUser= UserAuth::singleton()-> getUser();
 
  switch (@$_GET['op']) {
    case 'order':
      cartOrder($szHrefBase);
      return;
    case 'sendOrder':
      sendOrder($szHrefBase);
      return;
    case 'clear':
      cartClear($szHrefBase);
      break;
    case 'remove':
      removeFromCart($szHrefBase);
      return;
  }
 
  // avoid race condition
  checkCart(true);
 
  define('TITLE', 'Nákupní košík');
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
 
  $q= new DbQuery (
    "SELECT cart.route_id, UNIX_TIMESTAMP(route_date) AS route_date, UNIX_TIMESTAMP(route_date) AS route_time, ".
    "route_from, route_to, tickets.seat_id, tickets.price ".
    "FROM cart JOIN tickets USING (route_id,seat_id) JOIN routes USING (route_id)".
    "WHERE cart.user='$szUser' ".
    "ORDER BY route_date, seat_id"
    );
  if ($q->getNumRows()) {
    define('LEFT',   'text-align:left;');
    define('CENTER',  'text-align:center;');
    define('RIGHT',   'text-align:right;');
    define('TOP',     'vertical-align:top;');
    define('BOTTOM',  'vertical-align:bottom;');
    define('BOLD',    'font-weight:bold;');
    define('BORDER',  'border-right:1px solid gray;');
 
    $resTable= new QueryResultGroupBy ($canvas,
      Array (
        'Datum',
        'Odjezd',
        'Z',
        'Do',
        'Sedadlo',
        'Cena',
        'Jízdenka',
        'Cena celkem',
        '&nbsp;',
        '&nbsp;'
        ),
      Array (
        TOP.BOLD.RIGHT,
        TOP.BOLD.RIGHT,
        TOP.BOLD,
        TOP.BOLD.BORDER,
        RIGHT,
        RIGHT,
        CENTER.BORDER,
        BOTTOM.BOLD.RIGHT,
        BOTTOM.BOLD.CENTER,
        BOTTOM.BOLD.CENTER
        ),
      Array (true, true, true, true, 7=>true, true, true)
      );
    $lastRouteId= 0;
    $total= 0;
    for ($i=0; $i< $q->getNumRows(); $i++) {
      $row= $q->fetchArray();
      $bKey= ($lastRouteId!=$row['route_id']);
      $lastRouteId= $row['route_id'];
      unset ($row['route_id']);
      if ($bKey) {
        $subTotal= 0;
      }
      $row['route_date']= date ("j.n.Y", $row["route_date"]);
      $row['route_time']= date ("H:i", $row["route_time"]);
      $subTotal+= $row['price'];
      $total+= $row['price'];
      $row['price'].= '&nbsp;Kč';
      $row []= '<a href="'.$szHrefBase.'&amp;route='.$lastRouteId.'&amp;seat='.$row['seat_id'].'&amp;op=remove">vrátit</a>';
      $row []= '';
      $row []= '<a href="'.$szHrefBase.'&amp;route='.$lastRouteId.'&amp;op=remove">vrátit</a>';
      $row []= '<a href="'.Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=routes&amp;route='.$lastRouteId.'">přikoupit</a>';
      $resTable->addRow($row, $bKey);
      $keyTds= $resTable-> getKeyArray();
      $td= $keyTds[7];
      $td->replaceText ($subTotal.'&nbsp;Kč');
    }
    $tr=HtBlock::factory ('tr', $resTable, '.total');
    $td=HtInline::factory ('td', $tr, RIGHT, Array('colspan'=>8))-> addText('Celková cena jízdenek je&nbsp;&nbsp;&nbsp;<b>'.$total.'&nbsp;Kč</b>');
    $td=HtInline::factory ('td', $tr, LEFT, Array('colspan'=>2))-> addText('včetně DPH.');
 
    $div= HtInline::factory ('div', $canvas, '.summarySubmit');
    $form= HtInline::factory ('form', $div, '', Array(
      'method' => 'post',
      'action' => $szHrefBase.'&amp;op=order'
      ));
    HtSingle::factory ('input', HtInline::factory ('p', $form), 'width:12em;', Array (
      'type'   => 'submit',
      'value'  => 'Objednat'
      ));
 
    $menu= new Menu ('Nákupní košík');
    $menu-> addItem ($szHrefBase.'&amp;op=order', 'Objednat jízdenky');
    $menu-> addItem ($szHrefBase.'&amp;op=clear', 'Vysypat košík', (@$_GET['op']=='clear') ? '.menuItemSelected':'');
    $layout-> addToBegin ($menu);
  } else {
    emptyCartMessage();
  }
}
 
function removeFromCart($szHrefBase)
{
  $route= @$_GET['route'];
  $seat= @$_GET['seat'];
   if (!ini_get ("magic_quotes_gpc")) {
    // Security..
    $route= addslashes($route);
    $seat= addslashes($seat);
  }
  $szUser= UserAuth::singleton()-> getUser();
  $szQuery= "DELETE FROM cart WHERE user='$szUser' AND route_id='$route'";
  if (!empty ($seat))
    $szQuery .= " AND seat_id='$seat'";
  new DbQuery ($szQuery);
  Header ('Location: '.$szHrefBase);
  exit();
}
 
function cartOrder ($szHrefBase)
{
  define ('TITLE', 'Objednávka - náhled');
  define ('ORDER_MATURITY', strtotime('+21 days'));
 
  if (isCartEmpty()) {
    Header ('Location: '.$szHrefBase);
    exit();
  }
  $canvas= $GLOBALS['canvas'];
  $layout= $GLOBALS['layout'];
  $szUser= UserAuth::singleton()-> getUser();
  checkCart(true);
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
  if (isCartEmpty()) {
    emptyCartMessage();
    return;
  }
  $info= new SimpleInfoMulticol ($canvas, 2);
  $info-> setStyle('.infoFrame');
  $q= new DbQuery (
    "SELECT firms.ico AS ico, firms.name AS firm, firms.address AS address, users.name AS user ".
    "FROM users JOIN firms USING (ico) ".
    "WHERE user='$szUser'"
    );
  $row= $q->fetchArray();
  $info->addPair (0, 'Objednáno dne', date ("j.n.Y", time()));
  $info->addPair (0, 'Zaměstnancem',  $row['user'].' ('.$szUser.')');
  $info->addPair (0, NULL,            '');
  $info->addPair (1, 'IČO',           $row['ico']);
  $info->addPair (1, NULL,            '');
  $info->addPair (1, NULL,            '');
  $info->addPair (1, 'Firma',         $row['firm']);
  $info->addPair (1, NULL,            $row['address']);
 
  HtInline::factory ('h2', $canvas)-> addText('Jízdenky');
  $q= new DbQuery (
    "SELECT cart.route_id, UNIX_TIMESTAMP(route_date) AS route_date, UNIX_TIMESTAMP(route_date) AS route_time, ".
    "route_from, route_to, tickets.seat_id, tickets.price ".
    "FROM cart JOIN tickets USING (route_id,seat_id) JOIN routes USING (route_id)".
    "WHERE cart.user='$szUser' ".
    "ORDER BY route_date, seat_id"
    );
  define('LEFT',   'text-align:left;');
  define('RIGHT',   'text-align:right;');
  define('TOP',     'vertical-align:top;');
  define('BOTTOM',  'vertical-align:bottom;');
  define('BOLD',    'font-weight:bold;');
  define('BORDER',  'border-right:1px solid gray;');
 
  $resTable= new QueryResultGroupBy ($canvas,
    Array (
      'Datum',
      'Odjezd',
      'Z',
      'Do',
      'Sedadlo',
      'Cena jízdenky',
      'Cena celkem',
      '&nbsp;'
      ),
    Array (
      TOP.BOLD.RIGHT,
      TOP.BOLD.RIGHT,
      TOP.BOLD,
      TOP.BOLD.BORDER,
      RIGHT,
      RIGHT.BORDER,
      BOTTOM.BOLD.RIGHT
      ),
    Array (true, true, true, true, 6=>true, true)
    );
  $lastRouteId= 0;
  $total= 0;
  for ($i=0; $i< $q->getNumRows(); $i++) {
    $row= $q->fetchArray();
    $bKey= ($lastRouteId!=$row['route_id']);
    $lastRouteId= $row['route_id'];
    unset ($row['route_id']);
    if ($bKey) {
      $subTotal= 0;
    }
    $row['route_date']= date ("j.n.Y", $row["route_date"]);
    $row['route_time']= date ("H:i", $row["route_time"]);
    $subTotal+= $row['price'];
    $total+= $row['price'];
    $row['price'].= '&nbsp;Kč';
    $row []= '';
    $row []= '&nbsp;';
    $resTable->addRow($row, $bKey);
    $keyTds= $resTable-> getKeyArray();
    $td= $keyTds[6];
    $td->replaceText ($subTotal.'&nbsp;Kč');
  }
  $tr=HtBlock::factory ('tr', $resTable, '.total');
  $td=HtInline::factory ('td', $tr, RIGHT, Array('colspan'=>7))-> addText('Celková cena jízdenek je&nbsp;&nbsp;&nbsp;<b>'.$total.'&nbsp;Kč</b>');
  $td=HtInline::factory ('td', $tr, LEFT)-> addText('včetně DPH.');
 
  $info->addPair (0, 'K úhradě', $total.'&nbsp;Kč');
  $info->addPair (0, 'Splatnost do', date ("j.n.Y", ORDER_MATURITY));
 
  $div= HtBlock::factory ('div', $canvas, '.summarySubmit');
  $form= HtBlock::factory ('form', $div, '#orderEdit', Array(
    'method' => 'post',
    'action' => $szHrefBase
    ));
  HtSingle::factory ('input', HtInline::factory ('p', $form), '', Array (
    'type'   => 'submit',
    'value'  => 'Upravit objednávku'
    ));
  $form= HtBlock::factory ('form', $div, '#orderSend', Array(
    'method' => 'post',
    'action' => $szHrefBase.'&amp;op=sendOrder'
    ));
  $p= HtInline::factory ('p', $form);
  HtSingle::factory ('input', $p, '', Array (
    'name'   => 'sendOrder',
    'type'   => 'hidden',
    'value'  => 'true'
    ));
  HtSingle::factory ('input', $p, '', Array (
    'type'   => 'submit',
    'value'  => 'Závazně objednat'
    ));
  $menu= new Menu('Objednávka');
  class MyScript implements Text {
    public function draw()
    { ?>
<script type="text/javascript">
  function orderEdit()
  {
    x= document.getElementById("orderEdit");
    x.submit();
  }
  function orderSend()
  {
    x= document.getElementById("orderSend");
    x.submit();
  }
</script>
<?php
    }
  };
  Page::singleton()-> addToHead (new MyScript);
  $menu-> addItem('javascript:orderEdit();', 'Upravit objednávku');
  $menu-> addItem('javascript:orderSend();', 'Závazně objednat', 'font-weight:bold;');
  $layout-> addToBegin($menu);
}
 
function checkCart ($bAdvertise)
{
  if ($bAdvertise):
    $canvas= $GLOBALS['canvas'];
    $szUser= UserAuth::singleton()-> getUser();
    $q= new DbQuery (
      "SELECT cart.route_id, UNIX_TIMESTAMP(route_date) AS route_date, UNIX_TIMESTAMP(route_date) AS route_time, ".
      "route_from, route_to, tickets.seat_id, tickets.price ".
      "FROM order_items JOIN cart USING (route_id,seat_id) ".
      "JOIN tickets USING (route_id,seat_id) JOIN routes USING (route_id) ".
      "WHERE cart.user='$szUser' ".
      "ORDER BY route_date, tickets.seat_id"
      );
    $numRows= $q->getNumRows();
    if ($numRows) {
      HtInline::factory ('h2', $canvas)-> addText('Upozornění');
      HtInline::factory ('p', $canvas)-> addText('Následující jízdenky byly odebrány, protože již byly zakoupeny jiným uživatelem:');
 
      define('RIGHT',   'text-align:right;');
      define('TOP',     'vertical-align:top;');
      define('BOLD',    'font-weight:bold;');
      define('BORDER',  'border-right:1px solid gray;');
 
      $resTable= new QueryResultGroupBy ($canvas,
        Array (
          'Datum',
          'Odjezd',
          'Z',
          'Do',
          'Sedadlo',
          'Cena jízdenky'
          ),
        Array (
          TOP.BOLD.RIGHT,
          TOP.BOLD.RIGHT,
          TOP.BOLD,
          TOP.BOLD.BORDER,
          RIGHT,
          RIGHT.BORDER
          ),
        Array (true, true, true, true)
        );
      $lastRouteId= 0;
      for ($i=0; $i< $q->getNumRows(); $i++) {
        $row= $q->fetchArray();
        $bKey= ($lastRouteId!=$row['route_id']);
        $lastRouteId= $row['route_id'];
        unset ($row['route_id']);
        if ($bKey) {
          $subTotal= 0;
        }
        $row['route_date']= date ("j.n.Y", $row["route_date"]);
        $row['route_time']= date ("H:i", $row["route_time"]);
        $subTotal+= $row['price'];
        $row['price'].= '&nbsp;Kč';
        $resTable->addRow($row, $bKey);
      }
    }
  endif;
  new DbQuery (
    "DELETE cart FROM cart,order_items ".
    "WHERE cart.route_id=order_items.route_id AND cart.seat_id=order_items.seat_id"
    );
}
 
function isCartEmpty()
{
  $szUser= UserAuth::singleton()-> getUser();
  $q= new DbQuery (
    "SELECT COUNT(*) AS cnt FROM cart WHERE user='$szUser'"
    );
  $row= $q->fetchArray();
  return (1>$row['cnt']);
}
 
function emptyCartMessage()
{
  $p= HtInline::factory ('p', $GLOBALS['canvas']);
  $p-> addText('Váš nákupní košík je prázdný. Vyberte si, prosím, jízdenky z naší ');
  HtInline::factory ('a', $p, '', Array('href'=>Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=routes'))-> addText('nabídky');
  $p-> addText('.');
}
 
function sendOrder($szHrefBase)
{
  define ('ORDER_MATURITY', strtotime('+21 days'));
 
  checkCart(false);
  if (isCartEmpty() || @$_POST['sendOrder']!='true')
    redirTo($szHrefBase);
  $szUser= UserAuth::singleton()-> getUser();
  $ctime= time();
  $mat= ORDER_MATURITY;
  $q= new DbQuery (
    "INSERT INTO orders SET user='$szUser', ".
    "ctime=FROM_UNIXTIME($ctime), maturity=FROM_UNIXTIME($mat), paid_date=FROM_UNIXTIME(0)"
    );
  if ($q->getAffectedRows() !=1)
    redirTo($szHrefBase);
  $q= new DbQuery (
    "SELECT MAX(order_id) AS order_id FROM orders ".
    "WHERE user='$szUser'"
    );
  $row= $q->fetchArray();
  $order_id= @$row['order_id'];
  if (!$order_id)
    redirTo($szHrefBase);
  $q= new DbQuery (
    "INSERT INTO order_items (order_id, route_id, seat_id) ".
    "(SELECT $order_id AS order_id, route_id, seat_id ".
    "FROM cart WHERE user='$szUser')"
    );
  checkCart(false);
  $canvas= $GLOBALS['canvas'];
  define ('TITLE', 'Objednávka');
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
  $p= HtInline::factory ('p', $canvas);
  $p-> addText('Vaše ');
  HtInline::factory ('a', $p, '', Array('href'=>Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=orders&amp;order='.$order_id))->addText ('objednávka');
  $p-> addText(' byla <b>úspěšně odeslána</b>.');
  $p= HtInline::factory ('p', $canvas);
  $p-> addText('Všechny Vaše objednávky si můžete prohlédnout ');
  HtInline::factory ('a', $p, '', Array('href'=>Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=orders'))->addText ('zde');
  $p-> addText('.');
}
 
function redirTo ($to)
{
  Header ('Location: '.$to);
  exit();
}
 
function cartClear($szHrefBase)
{
  if (@$_POST['cartClear']=='true') {
    $szUser= UserAuth::singleton()-> getUser();
    new DbQuery ("DELETE FROM cart WHERE user='$szUser'");
    redirTo ($szHrefBase);
  }
 
  $canvas= $GLOBALS['canvas'];
  HtInline::factory ('h2', $canvas)-> addText('Vysypat nákupní košík');
  $block= HtBlock::factory ('div', $canvas, '.infoFrame');
  HtInline::factory ('p', $block)-> addText('Opravdu chcete nákupní košík vysypat a začít nakupovat znovu?');
  $yesno= HtBlock::factory ('div', $block, '.yesno');
  $form= HtInline::factory ('form', $yesno, '', Array(
    'method' => 'post',
    'action' => $szHrefBase.'&amp;op=clear'
    ));
  $div= HtInline::factory ('div', $form);
  HtSingle::factory ('input', $div, '', Array (
    'name'   => 'cartClear',
    'type'   => 'hidden',
    'value'  => 'true'
    ));
  HtSingle::factory ('input', $div, '', Array (
    'type'   => 'submit',
    'value'  => 'Ano'
    ));
  $form= HtInline::factory ('form', $yesno, '', Array(
    'method' => 'post',
    'action' => $szHrefBase
    ));
  $div= HtInline::factory ('div', $form);
  HtSingle::factory ('input', $div, '', Array (
    'type'   => 'submit',
    'value'  => 'Ne'
    ));
}
 
function pageOrders()
{
  $layout= $GLOBALS['layout'];
  $canvas= $GLOBALS['canvas'];
  $szUser= UserAuth::singleton()-> getUser();
  $szHrefBase=  Page::linkToWebRoot().'/dealer'.Page::phpFileExt().'?page=orders';
 
  $q= new DbQuery (
    "SELECT ico FROM users ".
    "WHERE user='$szUser'"
    );
  $row= $q->fetchArray();
  $ico= $row['ico'];
 
  if (isset ($_GET['order'])) {
    orderDetail ($ico, $szHrefBase);
    return;
  }
 
  define('TITLE', 'Objednávky');
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
 
  $q= new DbQuery (
    "SELECT orders.order_id, UNIX_TIMESTAMP(orders.ctime) AS ctime, ".
    "sum(tickets.price) AS total, users.name AS name, users.user, ".
    "UNIX_TIMESTAMP(orders.maturity) AS mat, UNIX_TIMESTAMP(orders.paid_date) AS paid ".
    "FROM orders JOIN order_items USING (order_id) ".
    "JOIN tickets USING (route_id,seat_id) ".
    "JOIN users ON orders.user=users.user ".
    "WHERE users.ico='$ico' ".
    "GROUP BY orders.order_id ".
    "ORDER BY order_id DESC"
    );
  $numRows= $q->getNumRows();
  if ($numRows) {
    define ('RIGHT', 'text-align:right;');
    define ('BOLD', 'font-weight:bold;');
    $table= new QueryResult ($canvas,
      Array('Č. obj.','Datum','Suma','Odpovědný uživatel','Stav','Položky'),
      Array(RIGHT, RIGHT, RIGHT.BOLD)
      );
    for ($i=0; $i<$numRows; $i++) {
      $row= $q->fetchArray();
      $order_id= $row['order_id'];
      $row['ctime']= date ("j.n.Y", $row["ctime"]);
      $row['name'].= ' (<b>'.$row['user'].'</b>)';
      unset($row['user']);
      $row['total'].= '&nbsp;Kč';
 
      if ($row['paid'])
        $row['mat']= '<b>zaplaceno</b> ('.date ("j.n.Y", $row["paid"]).')';
      else if ($row['mat']<time())
        $row['mat']= '<strong>! nezaplaceno !</strong>';
      else
        $row['mat']= 'splatnost do '.date ("j.n.Y", $row["mat"]);
      unset ($row['paid']);
 
      $linkToDetail=$szHrefBase.'&amp;order='.$order_id;
      $row['order_id']= '<a href="'.$linkToDetail.'">'.$order_id.'</a>';
      $row []= '<a href="'.$linkToDetail.'">zobrazit</a>';
      $table-> addRow($row);
    }
    $menu= new Menu ('Objednávky');
    $li= HtInline::factory ("li", $menu->getInnerList());
    HtInline::factory ('p', $li)-> addText('Vyberte si objednávku, pro zobrazení podrobnějších informací.');
    $layout-> addToBegin($menu);
  } else {
    HtInline::factory ('p', $canvas)-> addText('Vaše firma ještě nemá v informačním systému evidovány <b>žádné objednávky</b>. Těšíme se na Váš první nákup.');
  }
}
 
function orderDetail($ico, $szHrefBase)
{
  $order= $_GET['order'];
  if (!ini_get ("magic_quotes_gpc")) {
    // Security..
    $order= addslashes($order);
  }
 
  $q= new DbQuery (
    "SELECT users.user,users.name ".
    "FROM users JOIN orders USING (user) ".
    "WHERE ico=$ico AND order_id=$order"
    );
  if ($q->getNumRows() !=1)
    redirTo ($szHrefBase);
  $row= $q->fetchArray();
  $szUser= $row['user'];
  $szName= $row['name'];
 
  $q= new DbQuery (
    "SELECT name,address FROM firms ".
    "WHERE ico=$ico"
    );
  $row= $q->fetchArray();
  $szFirm= $row['name'];
  $szAddress= $row['address'];
 
  define('TITLE', 'Objednávka č. '.$order);
  $canvas= $GLOBALS['canvas'];
  $layout= $GLOBALS['layout'];
  HtTitle::singleton()-> setTitle(TITLE);
  HtInline::factory ('h1', $canvas)-> addText(TITLE);
 
  $info= new SimpleInfoMulticol ($canvas, 2);
  $info-> setStyle('.infoFrame');
  $q= new DbQuery (
    "SELECT UNIX_TIMESTAMP(ctime) AS ctime, ".
    "UNIX_TIMESTAMP(maturity) AS mat, ".
    "UNIX_TIMESTAMP(paid_date) AS paid ".
    "FROM orders WHERE order_id=$order"
    );
  $infoRec= $q->fetchArray();
  $info->addPair (0, 'Objednáno dne', date ("j.n.Y", $infoRec['ctime']));
  $info->addPair (0, 'Zaměstnancem',  $szName.' ('.$szUser.')');
  $info->addPair (0, NULL,            '');
  $info->addPair (1, 'IČO',           $ico);
  $info->addPair (1, NULL,            '');
  $info->addPair (1, NULL,            '');
  $info->addPair (1, 'Firma',         $szFirm);
  $info->addPair (1, NULL,            $szAddress);
 
  HtInline::factory ('h2', $canvas)-> addText('Položky objednávky');
  $q= new DbQuery (
    "SELECT order_items.route_id, UNIX_TIMESTAMP(route_date) AS route_date, UNIX_TIMESTAMP(route_date) AS route_time, ".
    "route_from, route_to, tickets.seat_id, tickets.price ".
    "FROM order_items JOIN tickets USING (route_id,seat_id) JOIN routes USING (route_id)".
    "WHERE order_items.order_id='$order' ".
    "ORDER BY route_date, seat_id"
    );
 
  define('LEFT',   'text-align:left;');
  define('RIGHT',   'text-align:right;');
  define('TOP',     'vertical-align:top;');
  define('BOTTOM',  'vertical-align:bottom;');
  define('BOLD',    'font-weight:bold;');
  define('BORDER',  'border-right:1px solid gray;');
  $resTable= new QueryResultGroupBy ($canvas,
    Array (
      'Datum',
      'Odjezd',
      'Z',
      'Do',
      'Sedadlo',
      'Cena jízdenky',
      'Cena celkem',
      '&nbsp;'
      ),
    Array (
      TOP.BOLD.RIGHT,
      TOP.BOLD.RIGHT,
      TOP.BOLD,
      TOP.BOLD.BORDER,
      RIGHT,
      RIGHT.BORDER,
      BOTTOM.BOLD.RIGHT
      ),
    Array (true, true, true, true, 6=>true, true)
    );
  $lastRouteId= 0;
  $total= 0;
  for ($i=0; $i< $q->getNumRows(); $i++) {
    $row= $q->fetchArray();
    $bKey= ($lastRouteId!=$row['route_id']);
    $lastRouteId= $row['route_id'];
    unset ($row['route_id']);
    if ($bKey) {
      $subTotal= 0;
    }
    $row['route_date']= date ("j.n.Y", $row["route_date"]);
    $row['route_time']= date ("H:i", $row["route_time"]);
    $subTotal+= $row['price'];
    $total+= $row['price'];
    $row['price'].= '&nbsp;Kč';
    $row []= '';
    $row []= '&nbsp;';
    $resTable->addRow($row, $bKey);
    $keyTds= $resTable-> getKeyArray();
    $td= $keyTds[6];
    $td->replaceText ($subTotal.'&nbsp;Kč');
  }
  $tr=HtBlock::factory ('tr', $resTable, '.total');
  $td=HtInline::factory ('td', $tr, RIGHT, Array('colspan'=>7))-> addText('Celková cena jízdenek je&nbsp;&nbsp;&nbsp;<b>'.$total.'&nbsp;Kč</b>');
  $td=HtInline::factory ('td', $tr, LEFT)-> addText('včetně DPH.');
 
  $info->addPair (0, 'K úhradě', $total.'&nbsp;Kč');
  $info->addPair (0, 'Splatnost do', date ("j.n.Y", $infoRec['mat']));
  $info->addPair (0, 'Zaplaceno', ($infoRec['paid']) ?
    'Ano, '.date ("j.n.Y", $infoRec['paid']) :
    'Ne'
    );
  $menu= new Menu('Objednávky');
  $menu-> addItem($szHrefBase, 'Vybrat jinou objednávku');
  $layout-> addToBegin($menu);
}
?>