<?php
session_start();
    header('Access-Control-Allow-Origin:*');
    header('Content-Type; application/json; charset=utf-8');
    header('Access-control-Allow-Method: POST');
    header('Access-control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-request-With');
    include('db.php');
        $inputdata = json_decode(file_get_contents("php://input"), true);
        
        $qte = $inputdata['qte'];
        $id = $inputdata['id'];
        $user = $inputdata['user'];
        
        $sel=$db->prepare('SELECT * FROM stock_boisson WHERE id=?');
        $sel->execute(array($id));
        while($sels=$sel->fetch()){
            $produit=$sels['boisson'];
            $qte_init=$sels['qte'];
        }
        
        //$rest=$qte_init-$qte;
        
        
            $pub=$db->prepare('UPDATE boisson SET qte_stock=qte_stock-? WHERE id=?');
            $pub->execute(array($qte_init,$produit));
            
            $bien=$db->prepare('UPDATE boisson SET qte_stock=qte_stock+? WHERE id=?');
            $bien->execute(array($qte,$produit));
        
        

        if ($pub && $bien) {
            $pubv=$db->prepare('INSERT INTO stock_boisson(user,boisson,qte,datt) VALUES(?,?,?,?)');

            $pubv->execute(array($user,$produit,$qte,date('Y-m-d')));
            
            if($pubv){
                 $ver=$db->prepare('UPDATE stock_boisson SET valid=? WHERE id=?');
                 $ver->execute(array(0,$id));
                 
                 echo(json_encode(['response' => 1]));
            } else{
                 echo(json_encode(['response' => 0]));
            }
           
        } else{
             echo(json_encode(['response' => 0]));
        }
        
        