<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" || $_SESSION["admin"] == false ) {
   mysqli_close($conn);
//   header("Location: index.php");
}

include_once('db_config.php');

$Start = $_SESSION["inicio"];
$Fin = $_SESSION["fin"];
//$Numero = $_SESSION["Asiento_Inicial"];
$Numero  = isset($_POST['numero']) ? $_POST["numero"] : "";
$Start = substr($Start,6,4) . "/" . substr($Start,3,2) . "/" . substr($Start,0,2);
$Fin = substr($Fin,6,4) . "/" . substr($Fin,3,2) . "/" . substr($Fin,0,2);
$Ejercicio = $_SESSION["ID_Ejercicio"];

echo $Numero . "<br/>";
if( empty($Numero) ) $Numero = 1;

if( !empty($Start) && !empty($Fin) ) {

   $sql = "BEGIN";
   $result = $conn->query($sql);
   mysql_free_result( $result );

   $asiento = intval( $Numero );
   $sql = "select * from asientos where Fecha >='" . $Start . "' and Fecha <='" . $Fin . "' and ejercicio='" . $Ejercicio . "' order by fecha, Asiento";
   $result = $conn->query($sql);
   if ($result->num_rows > 0) {

      while($row = $result->fetch_assoc()) {
         $sql = "update asientos set Asiento_Ordenado='" . $asiento . "', ordenado=1 where Id='" . $row["Id"] . "'";
         echo $sql . "<br/>";

         $result1 = $conn->query($sql);
         if (!$result1) break;  
         mysql_free_result( $result1 );

         ++$asiento;
      }

      mysql_free_result( $result );
      if( !$result1 ) {
         $sql = "ROLLBACK";
         $result = $conn->query($sql);
         echo "{\"command\":\"ROLLBACK\" }";
         echo "{\"status\":\"Error\" }";
      }
      else {
         $sql = "COMMIT";
         $result = $conn->query($sql);
         echo "{\"command\":\"COMMIT\" }";
         echo "{\"status\":\"Ok\" }";
      }
      mysql_free_result( $result );
   }
   mysqli_close($conn);
}
?>        

