<?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);

      
        $num_cmd = $inputdata['num_cmd'];
        $user = $inputdata['user'];

        $fon=$db->prepare('SELECT * FROM table_invoice_details WHERE num_cmd=?');
        $fon->execute(array($num_cmd));
        while ($fons=$fon->fetch()) {
            if (empty($fons['prix_repas'])) {
                $res1=$db->prepare('UPDATE boisson SET qte_stock=qte_stock+? WHERE id=(SELECT boisson FROM prix_boisson WHERE id=?)');
                $res1->execute(array($fons['qte'], $fons['prix_boisson']));
                
            } else {
                $set=$db->prepare('SELECT * FROM fiche_repas WHERE prix_repas=?');
                $set->execute(array($fons['prix_repas']));
                while ($sets=$set->fetch()) {
                    $quantit=$sets['qte']*$fons['qte'];
                    $res1=$db->prepare('UPDATE matiere_premiere SET qte_stock=qte_stock+? WHERE id=?');
                    $res1->execute(array($quantit, $sets['matiere_premiere']));
                }
                
            }
            
        }
        
            $res2=$db->prepare('DELETE FROM table_invoice_details WHERE num_cmd=?');
            $res2->execute(array($num_cmd));
            
            $res3=$db->prepare('INSERT INTO annulation_vente(user,num_cmd) VALUES(?,?)');
            $res3->execute(array($user,$num_cmd));
            
            $res4=$db->prepare('DELETE FROM tbl_invoice WHERE num_cmd=?');
            $res4->execute(array($num_cmd));
            
            if ($res2 && $res3 && $res4) {
                echo (json_encode(['response' => 1]));
            } else {
                echo (json_encode(['response' => 0]));
            }