<?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 WHERE id=?');
        $sel->execute(array($id));
        while($sels=$sel->fetch()){
            $produit=$sels['produit'];
            $qte_init=$sels['qte'];
        }
        
        $rest=$qte_init-$qte;
        
        if($rest < 0){
            // impossible de modifier la quantité stock car la quantité finale ne peut etre inférieure à 0
            echo(json_encode(['response' => -1]));
        } else{
            $pub=$db->prepare('UPDATE tbl_product SET pstock=pstock-? WHERE pname=?');

            $pub->execute(array($rest,$produit));
        }
        

        if ($pub) {
            $pubv=$db->prepare('INSERT INTO stock(user,produit,qte) VALUES(?,?,?)');

            $pubv->execute(array($user,$produit,$qte));
            
            if($pubv){
                 $ver=$db->prepare('UPDATE stock 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]));
        }
        
        