<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
	<script src="/js/jquery-2.1.0.min.js"></script>
	<script src="/js/jquery.redirect.js"></script>
	<script type="text/javascript">   
function Redirect() 
{  

if (('<?php echo $_POST['etatcom'] ?>' != '2')) {
$.redirect('index.html', {'dnumdevis': document.getElementById("dnumdevis").value , 'didxcli': document.getElementById("didxcli").value });
}	  else { 

//$.redirect('index.html', {'dnumdevis': document.getElementById("dnumdevis").value , 'didxcli': document.getElementById("didxcli").value });
    if ('<?php echo $_POST['choixfac'] ?>'=='complet') {
$.redirect('textefaccrea.php', {'dnumdevis': document.getElementById("dnumdevis").value , 'didxcli': document.getElementById("didxcli").value });
}
 if ('<?php echo $_POST['choixfac'] ?>'=='modele') {
$.redirect('listeclidevfac.php', {'dnumdevis': document.getElementById("dnumdevis").value , 'didxcli': document.getElementById("didxcli").value });
}	
} 
    
    } 
//document.write("You will be redirected to a new page in 5 seconds"); 
setTimeout('Redirect()', 450);   
</script>
	
	<style>
	
.attente{
	width:110px;
	height:110px;
	position:absolute;
	left:50%;
	top:50%;
	margin:-75px 0 0 -135px;
}
	</style>
	<img class="attente" src="spinner.gif">
	<?php 

	$debug=1;

 $myboxes = $_POST['DES'];
 $myboxes1 = $_POST['QTE'];  
 $myboxes2 = $_POST['PRIX']; 
 $myboxes3 = $_POST['UNITE'];  
 $myboxes4 = $_POST['ORDRELIGNE'];  
	$NumeroIndexDevis=$_POST['dnum'];
	$NumeroIdxClient=$_POST['didxcli'];
	$TYPECHOIX=$_POST['choixfac'];
 $ordl = $_POST['ligne'];
 $RechIdx = $_POST['dnum'];	
	
	if ($debug==1)   { 
	print "idex devis ".$_POST['dnum']; //numeros idxdevis
	print "<br> Idx client ".$_POST['didxcli'];
	print "<br> date devis ".$_POST['ddate'];
	print "<br> Objet ".$_POST['object'];
	print "<br> chantier ".$_POST['dchantier'];
	print "<br> tva ".$_POST['dtva'];
	print "<br> banque ".$_POST['dbanque'];
	print "<br> Remarque ".$_POST['dremarque'];
	print "<br> Memo ".$_POST['dmemo'];
	print "<br> Etat ".$_POST['etatcom'];
	print "<br> Type ".$_POST['typetravail'];
	print "<br> Commande ".$_POST['commande'];
	} 
	
	
	//update tete
	
$DNUM=$_POST['devisnum'];
$DDATE=$_POST["ddate"];
$DOBJET=$_POST["object"];
$DIDXCLI=$_POST["didxcli"];
$DCHANTIER=$_POST["dchantier"];
$DTVA=$_POST["dtva"];
$DBANQUE=$_POST["dbanque"];
$DREMARQUE=$_POST["dremarque"];
$MEMO=$_POST['dmemo'];
	
$ETATC=$_POST["etatcom"];
$TYPEC=$_POST["typetravail"];
$today = date("Y-m-d"); 

$COMMANDE=$_POST['commande'];
$MONTANTHTVA=$_POST['total'];
		
					 
				
			        // on se connecte à notre base devis

$servername = "localhost:8889";
$username = "root";
$password = "root";
$dbname = "devis";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

 //$sql = "SELECT * FROM tete";
	
//$sql = "UPDATE tete SET num='$DNUM', date='$DDATE', objet='$DOBJET', idxcli='$DIDXCLI', chantier='$DCHANTIER', tva='$DTVA', banque='$DBANQUE', remarque='$DREMARQUE',memo='$MEMO' WHERE idx='$NumeroIndexDevis' ";
	$sql = "UPDATE tete SET etat='$ETATC', type='$TYPEC', live='1',montant='$MONTANTHTVA' WHERE idx='$NumeroIndexDevis' ";
			 
if ($debug==1)   { print $sql;  print "<br>"; } 
$result = $conn->query($sql);

    $sql = "UPDATE tete SET UPDATE commande=CASE 
    
    WHEN commande ='0000-00-00' THEN
          NOW()
        ELSE ''
        END 
        
        WHERE idx='$NumeroIndexDevis' ";

     { print $sql;  print "<br>"; } 
    $result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        //echo "Num: " . $row["dnum"]. " - Date: " . $row["ddate"]. " - Objet: " . $row["objet"]. " Idex" . $row["didxcli"]. "<br>";
		//echo "Soc: " . $row["societe"]. " - Nom: " . $row["nom1"]. "  " . $row["nom2"]. "<br>";
    } 
	
	
	
	} else {
   if ($debug==1)   { echo "0 results";} 
}

    $sql = "SELECT * FROM tete  WHERE idx='$NumeroIndexDevis' ";
     $result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    $NumeroIdxClient=$row["idxcli"];
        $DNUM=$row["num"];
        //echo "Num: " . $row["dnum"]. " - Date: " . $row["ddate"]. " - Objet: " . $row["objet"]. " Idex" . $row["didxcli"]. "<br>";
		//echo "Soc: " . $row["societe"]. " - Nom: " . $row["nom1"]. "  " . $row["nom2"]. "<br>";
    } 
	
	
	
	} else {
   if ($debug==1)   { echo "0 results";} 
}
    
$conn->close();
			 
	// mise à jour pour calendrier /////////
    
     // on se connecte à notre base pour planning

$servername = "localhost:8889";
$username = "root";
$password = "root";
$dbname = "calendrier";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
    // retrouve la dernière date //

    $sql = "  SELECT max(`Fin`) as MAXDATE FROM planning " ;
 print "<br>".$sql;	
   
    // convertit en nombre
      $floatMontant  = floatval(preg_replace('/\s+/', '',$MONTANTHTVA));
    	 print "<br>Montant : ".($floatMontant)."<br>";
	 
$resultD = $conn->query($sql);
        if ($resultD->num_rows > 0) {
    // output data of each row
    while($row = $resultD->fetch_assoc()) {
		
$DateFinMax=$row["MAXDATE"];

    } 
    
	
	} else {
   // echo "0 results";
}

            
 $sql = "  SELECT * FROM planning WHERE IdxDevis=".$NumeroIndexDevis."  ";
print "<br>".$sql;	
   $resultD = $conn->query($sql);
    $Suite=0;
    // si commande déjà existante
    
        if ($resultD->num_rows > 0) {
    // output data of each row
            
    print "commande existante dans planning";
              $Suite=0;
              $conn->close(); 
            
  //  while($row = $resultD->fetch_assoc()) {
    
//		print "<br>ici".$DateFinMax."<br>";

  //      $DateDebut=date("Y-m-d", strtotime($row["Debut"]));
  //       print "<br>".$DateDebut."<br>";
  //    
  //      print "<br>".($floatMontant/1000)."<br>";
  //      $DateAjout=intval(ceil(($floatMontant/1000)));
  //      $DateAjout++; 
       
 //$DateFin= date('Y-m-d', strtotime( $DateDebut .'+ '.$DateAjout.'days'));    
 //       print "<br>".$DateDebut."/".$DateAjout."/".$DateFin."----------------<br>";
//$sql1 = "UPDATE `planning` SET Debut='".$DateDebut."', Fin= '".$DateFin."', IdxDevis='".$NumeroIndexDevis."', IdxClient= '".$NumeroIdxClient."' WHERE  IdxDevis='".$NumeroIndexDevis."'  ";
 //      
   //     print "<br>".$sql1;	
  //      
     //   $resultD = $conn->query($sql1);
      
           
 //   } 
    
	 // si commande NON existante
	} else {
            
             print "commande NON existante dans planning";
             print "<br>jour sem : ".$DateFinMax."<br>";
            
            /// mise en place de la periode de préparation ///
        $DateDebut=date("Y-m-d", strtotime($DateFinMax . " - 5 day"));  
        $DateAjout=intval(ceil(($floatMontant/1000))); 
        $WeekEndDeport=0;
          
           $DateAjout=0;
        
            $JourSem=date("w",strtotime($DateDebut));
            print "<br>jour sem : ".$JourSem."<br>";
            switch ($JourSem) {
    case 0:
        echo "Dimanche";
        $DateAjout++; 
        $DateAjout++; 
        $DateAjout++; 
        $DateAjout++;
        $WeekEndDeport=0;
        break;
    case 6:
         echo "Samedi";
        $DateAjout++; 
        $DateAjout++; 
        $DateAjout++; 
        $WeekEndDeport=0;            
        break;
    case 5:
          echo "vendredi";
        $DateAjout++; 
        $DateAjout++;        
        $WeekEndDeport=0;            
        break;
}
            $DateDebut=date('Y-m-d', strtotime( $DateDebut .'- '.$DateAjout.'days')); 
              $DateAjout=2;
            $DateFin= date('Y-m-d', strtotime( $DateDebut .'+ '.$DateAjout.'days'));    
             print "<br>".$DateDebut."/".$DateAjout."/".$DateFin."<br>";
 
         // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}    
            $sql = "INSERT INTO planning (Titre, Debut, Fin, Description,Lien,CouleurFonds,IdxDevis,IdxClient) VALUES ('".$DNUM." Préparation.',  '".$DateDebut."','".$DateFin."','<br>','0','#247106','".$NumeroIndexDevis."','".$NumeroIdxClient."')  ";
      print "<br>".$sql;
            
      $resultD = $conn->query($sql);      
       $conn->close(); 
    print "mise a jour SUIte <br>";
            $Suite=1;

}
 
    
    
  
    
    if ($Suite == 1 ) {
         // on se connecte à notre base pour planning pour mise à jour lien et parent
print "suite = 1 . Mise a jour lien parent<br>";
$servername = "localhost:8889";
$username = "root";
$password = "root";
$dbname = "calendrier";

        
        $DateDebutMath=date("Y-m-d", strtotime($DateFinMax . " + 0 day"));   
       
        $DateAjout=intval(ceil(($floatMontant/1000)));
        $WeekEndDeport=0;
        
        
        
        $DateAjout++;
        $DateAjoutWE=0;
        
            print "<br>dernier jour pour start  : ".$DateFinMax."<br>";
            print "<br>dernier jourMath pour start  : ".$DateDebutMath."<br>";
            $JourSem=date("w",strtotime($DateDebutMath));
            print "<br>jour sem : ".$JourSem."<br>";
            switch ($JourSem) {
    case 0:
        echo "Dimanche";
        $DateAjoutWE++; 
        $WeekEndDeport=0;
        break;
    case 6:
         echo "Samedi";
        $DateAjoutWE++; 
        $DateAjoutWE++; 
        $WeekEndDeport=0;            
        break;
    case 5:
          echo "vendredi";
          $WeekEndDeport=0;            
        break;
}
        $DateDebut=date('Y-m-d', strtotime( $DateDebutMath .'+ '.$DateAjoutWE.'days')); 
        $DateFin= date('Y-m-d', strtotime( $DateDebut .'+ '.$DateAjout.'days'));   
        
        
        
        
        
          print "<br>".$DateDebut."/".$DateAjout."/".$DateFin."<br>";
    
        
        
        /// comptage des WeekEnd ///////
        
       $begin = new DateTime( $DateDebut );
        $end   = new DateTime($DateFin );
       
          echo $end->format("Y-m-d")."<- date fin comptage <br>"; 
for($iwe = $begin ; $iwe <=  $end ; $iwe->modify('+1 day')){
    //        echo $iwe->format("Y-m-d")."<br>"; 
            $testjour=$iwe->format("Y-m-d");
            $JourSem=date("w",strtotime($testjour));
      //      print "<br>jour sem : ".$JourSem."<br>";
            switch ($JourSem) {
    case 0:
        //echo "Dimanche";
          $WeekEndDeport++;
        break;
    case 6:
         //echo "Samedi";
          $WeekEndDeport++;            
        break;
                }
}
      
if ($WeekEndDeport % 2 == 0) {
 // print "NOMBRE PAIR";
}else{$WeekEndDeport++;    }
        
    print "<br> WEEK end jours : ".$WeekEndDeport."/<br>";    
    
        // si date fin est samedi ou dimanche
        $DateAjoutSupp=0;
            $JourSem=date("w",strtotime($DateFin));
            print "<br>jour sem : ".$JourSem."<br>";
            switch ($JourSem) {
    case 0:
        echo "Dimanche";
        $DateAjoutSupp++;
        $DateAjoutSupp++; 
       break;
    case 6:
        echo "Samedi";
        $DateAjoutSupp++; 
        $DateAjoutSupp++; 
        $DateAjoutSupp++; 
        break;
    
}
        
        $DateFin= date('Y-m-d', strtotime( $DateFin .'+ '.$DateAjoutSupp.'days'));   
        
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
    
	       $sql = "  SELECT `Idx` as IDXMODIF FROM planning  WHERE IdxDevis='".$NumeroIndexDevis."'  ";
           print "<br>".$sql;	
           $resultD = $conn->query($sql);
             if ($resultD->num_rows > 0) {
    // output data of each row
    while($row = $resultD->fetch_assoc()) {
            
                 
 print "<br>-->".$row["IDXMODIF"]."<br>";
        $IndexLineModif=$row["IDXMODIF"];
        }  
           $sql = "INSERT INTO planning (Titre, Debut, Fin,  Description,Lien,CouleurFonds,IdxDevis,IdxClient) VALUES ('".$DNUM."', '".$DateDebut."','".$DateFin."','<br>','".$IndexLineModif."','#000000','".$NumeroIndexDevis."','".$NumeroIdxClient."')  ";      
   print "<br>".$sql;	
   $resultD = $conn->query($sql);      
          }  
   // echo "0 results";
 
   $conn->close();  
	      }  

?>
	
			<form method = "post" action = "indexdevlecture.php">	

			<input type="hidden" size="60" name="dnumdevis" id="dnumdevis" value="<?php echo $NumeroIndexDevis; ?>" > 
		
       		<input type="hidden" size="60" name="didxcli" id="didxcli" value="<?php echo $NumeroIdxClient; ?>" >
			
			<input type = "hidden" type = "submit" id = "update" value = "suivant"><br> 
	

<body>
</body>
</html>