<?php
# Tarif_edit_detail_module ver.1.0
# last modification 16.3.2010
# Formulář pro úpravu vybraného tarifu(položky)
#

if (IsSet($_GET['idTARIF'])){$_SESSION['idTARIF']=$_GET['idTARIF'] ;}
################################################################################
# Update dat trunkU K TARIFU 
################################################################################

  //tady prepsat na dotaz jeslti ze existuje idtrunk ve val 1 z prom get idtrunk
  
#-------------------------------------------------------------------------------        
//echo $_SESSION['idTARIF'];  
//echo $_SESSION['idTRUNK'];
################################################################################
################################################################################

################################################################################
################################################################################
################################################################################ 
if (!IsSet($_SESSION['ted_buffer']) || IsSet($_GET['TED_INTERVALS_CANC'])){
      unset ($_SESSION['ted_buffer']);
      $_SESSION['ted_buffer']=array();
      include "build/db_connect.inc.php"  ;
      $query="SELECT BP.uptotime,BP.unionnum
              FROM billing_period BP
              JOIN spec_billing_period SBP ON SBP.idBILLINGPERIOD=BP.idBILLINGPERIOD
                    AND SBP.validity=1 AND BP.validity=1
              WHERE SBP.idTARIF=".$_SESSION['idTARIF']."";
      $result = mysql_query($query);
      if (!$result) {
          die('Tarifní intervaly nelze načíst do pole:' . mysql_error());
      }
      while(list($uptotime,$unionnum)=mysql_fetch_row($result)){
        $_SESSION['ted_buffer'][]=array($uptotime,$unionnum);  
      }
    }
################################################################################

if (IsSet($_GET['TED_INTERVALS'])){
 
    include "build/db_connect.inc.php"  ;
    $query="START TRANSACTION";
    $result = mysql_query($query);
    if (!$result) {
        die('Transakci nelze nastartovat:' . mysql_error());
    }
    $query="UPDATE spec_billing_period SET validity=0 
            WHERE
            idTARIF=".$_SESSION['idTARIF']." ";
        if (count($_SESSION['ted_buffer'])>0)
        {     
           $query=$query." AND idBILLINGPERIOD NOT IN( ";
#-------------------------------------------------------------------------------            
            for ($a=0;$a<count($_SESSION['ted_buffer']);$a++){
                $subquery="SELECT idBILLINGPERIOD 
                            FROM billing_period
                            WHERE 
                            uptotime=".$_SESSION['ted_buffer'][$a][0]."
                            AND  unionnum=".$_SESSION['ted_buffer'][$a][1]."
                          ";
                $result = mysql_query($subquery);
                if (!$result) {
                    die('Položky nelze načist:' . mysql_error());
                }
                list($idBILLINGPERIOD)=mysql_fetch_row($result);
                $query=$query.$idBILLINGPERIOD." ";
                if ($a<(count($_SESSION['ted_buffer'])-1)){$query=$query.",";}
            }
            $query=$query." )";
        }
        $result = mysql_query($query);
        if (!$result) {
            die('1Transakci nelze nastartovat:' . mysql_error());
        }
        
#-------------------------------------------------------------------------------
  for ($a=0;$a<count($_SESSION['ted_buffer']);$a++){ 
            echo("haha ".count($_SESSION['ted_buffer']));
  $query="SELECT BP.idBILLINGPERIOD,SBP.validity
           FROM billing_period BP
           JOIN spec_billing_period SBP ON BP.idBILLINGPERIOD=SBP.idBILLINGPERIOD
                AND BP.validity=1 
           WHERE BP.uptotime=".$_SESSION['ted_buffer'][$a][0]."
           AND BP.unionnum=".$_SESSION['ted_buffer'][$a][1]."
           AND SBP.idTARIF=".$_SESSION['idTARIF']."";
    $result = mysql_query($query);
    if (!$result) {
        die('Data nelze načíst:' . mysql_error());
    }
//    echo("vypis ".$_SESSION['ted_buffer'][$a][0].$_SESSION['ted_buffer'][$a][1]);
//    echo "zazn: ".mysql_num_rows($result);
    if (mysql_num_rows($result)==0){
        $subquery="INSERT INTO spec_billing_period (idTARIF,idBILLINGPERIOD)
                SELECT ".$_SESSION['idTARIF'].",idBILLINGPERIOD
                FROM billing_period
                WHERE uptotime=".$_SESSION['ted_buffer'][$a][0]."
                AND unionnum=".$_SESSION['ted_buffer'][$a][1]."";
        $subresult = mysql_query($subquery);
        if (!$subresult) {
            die('Data nelze vložit:' . mysql_error());
        }
    }
    else{
//        echo("hahass");                                                                              
        list($idBILLINGPERIOD,$validity)=mysql_fetch_row($result);       
//          echo "validita=".$validity;
            if ($validity==0){
                $query="UPDATE spec_billing_period SET validity=1 
                        WHERE idBILLINGPERIOD=".$idBILLINGPERIOD."    
                        AND idTARIF=".$_SESSION['idTARIF']."";
                $result = mysql_query($query);
                if (!$result) {
                    die('Data nelze aktualizivoat:' . mysql_error());
                }
            }
    }
  }
   $query="COMMIT";
   $result = mysql_query($query);
//    echo("haha");
    
}


 
################################################################################

if (IsSet($_GET['TED_UNSELECT'])){
#odstraneni zaznamu z bufferu uchov8van0ho v session;bufer zacina od 0 proto get.. -1
array_splice($_SESSION['ted_buffer'],$_GET['TED_UNSELECT']-1,1);//vymazani polozky 2.pozice 
}
#Uložení vybrané hodnoty do bufferu, neni li už v bufferu obsažena                
if (IsSet($_GET['TED_SELECT']) && !in_array(array($_GET['TED_UPTOTIME'],$_GET['TED_UNION']),$_SESSION['ted_buffer'])){
    $_SESSION['ted_buffer'][]=array($_GET['TED_UPTOTIME'],$_GET['TED_UNION'])   ;
}
 

################# Obecne udaje #################################################  
function TED_checkForm()
  {
    if ($_POST['TED_COST']=="" ) 
       return false;
       
#DOPLNIT SABLONU POUYE PRO CISLA
  //  if ($_GET['TED_COST']!= ereg("^[0123456789]+$",$_GET['TED_COST']))
    //   return "U ceny může být pouze číselná hodnota";

       
    return true;
  }
  if (IsSet($_POST['TED_SUBMITED']))
  {
   $vysledek=TED_checkForm();       //volání funkce pro kontrolu údajů dle šablon
  

   if ($vysledek===TRUE)
   {  #Dotaz, jestli už existuje v tab union_cost stanovena cena jednotky
     include "build/db_connect.inc.php"  ;
     $query="SELECT idCENAJEDNOTKY 
              FROM union_cost
              WHERE cost=".$_POST['TED_COST']."";
     $result = mysql_query($query);
     if (mysql_num_rows($result)==0)
     {  #Jestli stanovena cena neexistuje, vytvoří se požadovaná položka v union_cost
        # a zahájí se transakce se transakce
        $trans="START TRANSACTION";
        $result =  mysql_query($trans);
        $query="INSERT INTO union_cost (cost) 
                VALUES (".$_POST['TED_COST'].")";
        $result = mysql_query($query);
        if (!$result) {
          die('Aktualizace dat nebyla zapsána:' . mysql_error());
        }
        $query="SELECT last_insert_id()";
        $result = mysql_query($query);
        if (!$result) {
          die('Aktualizace dat nebyla zapsána:' . mysql_error());
        }
        list($idCENAJEDNOTKY) = mysql_fetch_row($result);
     }
     else{ # jestli položka už existuje, tak se pouze načte
        list($idCENAJEDNOTKY) = mysql_fetch_row($result)  ;
     }
   }
    else{
    $idCENAJEDNOTKY="NULL"; }
    if ($vysledek===TRUE || $vysledek===FALSE) {
     # update záznamu v tabulce tarif s údaji z formuláře a idCENAJEDNOTKY z tab
     # union_cost                  
    include "build/db_connect.inc.php"  ;
    $query="UPDATE tarif SET Name=\"".$_POST['TED_NAME']."\",idCENAJEDNOTKY=".$idCENAJEDNOTKY.",
                              description=\"".$_POST['TED_DESCRIPTION']."\", ";
     if(!IsSet($_POST['TED_VALIDITY'])) {
        $query=$query."validity=0";
    }
    else
    {
      $query=$query."validity=".$_POST['TED_VALIDITY']."";
    }                       
    $query=$query." WHERE idTARIF=".$_SESSION['idTARIF']."";
    $result = mysql_query($query);
    if (IsSet($trans)){
      $trans="COMMIT";
      $result =  mysql_query($trans);
      unset($trans);
    }
    if (!$result) {
      echo ($query);
      die('Aktualizace dat nebyla zapsána:' . mysql_error());
    }

    }
    else {echo($vysledek) ;}
 } 
 
 
 
 
  #načteni údajů k vybranému tarifu do formuláře.
  include "build/db_connect.inc.php"  ;
  $query="SELECT T.Name,T.idCENAJEDNOTKY,UC.cost,T.description,T.validity
          FROM tarif T
          LEFT JOIN union_cost UC on UC.idCENAJEDNOTKY=T.idCENAJEDNOTKY AND UC.validity=1
          WHERE T.idTARIF=\"".$_SESSION['idTARIF']."\"
          ";
  $result = mysql_query($query);
  if (!$result) {
      die('Informace o tarifu nelze načíst. ' . mysql_error());
  }
  list($tarifname,$T_idCENAJEDNOTKY,$costperunion,$description,$validity) = mysql_fetch_row($result)  ;


?>
<script language="JavaScript">
var MaxLengthLock = false;
      function MaxLengthCount(fieldObj,fieldMaxLength)
      {
        if (!MaxLengthLock)
        {
          MaxLengthLock = true;
          if (fieldObj.value.length > fieldMaxLength)
          {
            alert("Text je delší než " + fieldMaxLength + " znaků!");
            fieldObj.value = fieldObj.value.substring(0,fieldMaxLength);
          }
          var percentage = parseInt(100 - (( fieldMaxLength - fieldObj.value.length) * 100)/fieldMaxLength);
          document.getElementById(fieldObj.id + "_PBar").style.width = parseInt((parseInt(fieldObj.offsetWidth)*percentage)/100)+"px";
          MaxLengthLock = false;
        }
      }
      </script>
<center>
<div class="forms">
  <h3>Detail/editace tarifu</h3><span class="backtoform"><a href="admin_page.php?NEXTFORM=10">Zpět</a> </span>
  <fieldset>
    <legend>Obecné info</legend>
  <form action="admin_page.php" method="post">
    <table style="width:500px">
      <tr>
        <td class="tableculombhead" style="text-align:right" colspan=3>Aktivní:  <input type="checkbox" name="TED_VALIDITY"  value="1"<?php if ($validity==1)  echo "checked";?>></td>
      </tr><tr>
        <td class="tablehead" style="width:20px">ID</td>
        <td class="tablehead" >Název tarifu</td>
        <td class="tablehead" >Cena jednotky</td>
      </tr><tr>
        <td class="tableculombhead" style="width:20px"><input type="text" size=1   name="idTARIF" value="<?php echo($_SESSION['idTARIF']); ?>" disabled ></td>
        <td class="tableculombhead"><input type="text"  name="TED_NAME" value="<?php echo($tarifname); ?>"></td>
        <td class="tableculombhead"><input type="text" size=1 name="TED_COST" value="<?php echo($costperunion); ?>"></td>            
      </tr><tr>
        <td class="tablehead" colspan=3>Popis: </td>
      </tr><tr>
         <td colspan=3><textarea cols="60" name="TED_DESCRIPTION" id="TED_DESCRIPTION" style="max-width:500px" wrap="virtual"
                                          onpropertychange="MaxLengthCount(this,160);"
                                          onclick="MaxLengthCount(this,160);"
                                          onmousemove="MaxLengthCount(this,160);"
                                          onblur="MaxLengthCount(this,160);"
                                          onkeyup="MaxLengthCount(this,160);"
                                          onfocus="MaxLengthCount(this,160);"
                                          onchange="MaxLengthCount(this,160);"
                                          onafterupdate="MaxLengthCount(this,160);"><?php echo($description); ?></textarea>   
         <div id="TED_DESCRIPTION_PBar" style="width:0px;height:10px;border:0;font-size:8px;overflow:hidden;background-color: #3399FF;"></div>
         </td>
      </tr><tr>
        <input type="hidden" name="TED_SUBMITED" value="TRUE">
        <td class="tableculombhead" colspan=3 align="right"><input type="reset" value="Zruš změny"><input type="submit" value="Ulož">  </td>
      </tr>
                
    </table>
  </form>
  </fieldset>
<?php
################################################################################
################# Formulář pro edit účtovacích intervalů #######################
  include "build/db_connect.inc.php"  ;
  $query="SELECT uptotime,unionnum 
            FROM billing_period
            WHERE validity=1
              ";
  #------------------------------
  if (count($_SESSION['ted_buffer'])>0){
      $query=$query."AND uptotime NOT IN(";          
      for ($i=0;$i<count($_SESSION['ted_buffer']);$i++){
          if ($i+1!=count($_SESSION['ted_buffer'])){
              $query=$query.$_SESSION['ted_buffer'][$i][0].",";
          }else{
              $query=$query.$_SESSION['ted_buffer'][$i][0].")";
          }
      }
  }
  
  
  $query=$query." ORDER BY uptotime ASC";
  $result = mysql_query($query);
  if (!$result) {
      die('Předvýběr nelze načíst:' . mysql_error());
  }
?>

<fieldset>
    <legend>Účtovací intervaly</legend>
    <div class="userlist">
      <table align="center" width="500px">
        <tr>
            <td colspan=3 style="text-align:center;background-color:black;color:white">Předvýběr</td>
            <td colspan=3 style="text-align:center;background-color:black;color:white">Po dokončení editace</td>
        </tr><tr>
            <td style="text-align:center;background-color:grey;color:white">Interval</td>
            <td style="text-align:center;background-color:grey;color:white">Počet jednotek</td>
            <td style="width:20px"> </td><td style="width:20px"> </td>
            <td style="text-align:center;background-color:grey;color:white">Interval</td>
            <td style="text-align:center;background-color:grey;color:white">Počet jednotek</td>
        </tr>
      <?php
        $poradizaznamu = 0;
        if (mysql_num_rows($result) >count($_SESSION['ted_buffer'])){
            $i=0;
            while (list($uptotime,$unionnum) = mysql_fetch_row($result)) {
                echo "<tr>";
                echo "<td>".$uptotime."</td><td>".$unionnum."</td><td style=\"text-align:right;width:20px\"><a href=\"".selfURL()."?TED_SELECT=TRUE&TED_UPTOTIME=".$uptotime."&TED_UNION=".$unionnum."\"><img src=\"files/pictures/vyber.gif\" alt=\"Vyber\"></a></td>";
                if ($i<count($_SESSION['ted_buffer'])){
                    $poradizaznamu++;
                    echo ("<td style=\"width:20px\"><a href=\"".selfURL()."?TED_UNSELECT=".$poradizaznamu."&TED_UPTOTIME=".$_SESSION['ted_buffer'][$i][0]."&TED_UNION=".$_SESSION['ted_buffer'][$i][1]."\"><img src=\"files/pictures/odstran.gif\"></a></td><td>".$_SESSION['ted_buffer'][$i][0]."</td><td>".$_SESSION['ted_buffer'][$i][1]."</td>");
                }
            echo "</tr>";
            $i++; 
            }
       }
       else{
            for ($a=0;$a<count($_SESSION['ted_buffer']);$a++){
                if ($a<mysql_num_rows($result)){
                echo "<tr>";
                list($uptotime,$unionnum) = mysql_fetch_row($result);
                echo "<td>".$uptotime."</td><td>".$unionnum."</td><td style=\"text-align:right;width:20px\"><a href=\"".selfURL()."?TED_SELECT=TRUE&TED_UPTOTIME=".$uptotime."&TED_UNION=".$unionnum."\"><img src=\"files/pictures/vyber.gif\" alt=\"Vyber\"></a></td>";
                }
            else{
                echo "<td></td><td></td><td></td>";}
                $poradizaznamu++;
                echo ("<td style=\"width:20px\"><a href=\"".selfURL()."?TED_UNSELECT=".$poradizaznamu."&TED_UPTOTIME=".$_SESSION['ted_buffer'][$a][0]."&TED_UNION=".$_SESSION['ted_buffer'][$a][1]."\"><img src=\"files/pictures/odstran.gif\"></a></td><td>".$_SESSION['ted_buffer'][$a][0]."</td><td>".$_SESSION['ted_buffer'][$a][1]."</td>");
                echo "</tr>";
            }
      }
      //echo "zaznamu: ".mysql_num_rows($result);
      ?>
  </table>
  </div>
  <table align="center">
      <tr> 
      <td align="right"><form action="admin_page.php" method="get">
          <input type="hidden" name="TED_INTERVALS_CANC">
          <input align="right" type="submit" value="Zruš změny"> 
          </form>
       </td><td>
          <form action="admin_page.php" method="get">
          <input type="hidden" name="TED_INTERVALS" value="TRUE">
          <input align="right" type="submit" value="Ulož">
          </form>
      </td</tr>
  </table>
</fieldset>
<?php
################################################################################
################# Formulář pro edit předvoleb ##################################


?>  


</div>
</center>