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

      
        $id = $inputdata['id'];

        $fon=$db->prepare('SELECT * FROM table_invoice_details WHERE id=?');
        $fon->execute(array($id));
        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']));
                $res2=$db->prepare('DELETE FROM table_invoice_details WHERE id=?');
                $res2->execute(array($id));
                
                if ($res1 && $res2) {
                    echo (json_encode(['response' => 1]));
                } else {
                    echo (json_encode(['response' => 0]));
                }
                
            } 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']));
                }
                $reqt=$db->prepare('UPDATE prix_repas SET qte_stock=qte_stock+? WHERE id=?');
                $reqt->execute(array($fons['qte'], $fons['prix_repas']));
                $res2=$db->prepare('UPDATE table_invoice_details SET valid=0 WHERE id=?');
                $res2->execute(array($id));
                
                if ($res2) {
                    echo (json_encode(['response' => 1]));
                } else {
                    echo (json_encode(['response' => 0]));
                }
                
            }
            
        }