<?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);
        $prix_boisson = $inputdata['prix_boisson'];
        $qte = $inputdata['qte'];
        $num_cmd = $inputdata['num_cmd'];
        $user = $inputdata['user'];
        
        $pub=$db->prepare('SELECT * FROM point_journalier WHERE user=? AND ouverture=? AND fermeture=? ORDER BY id DESC LIMIT 1');
        $pub->execute(array($user, 1, 0));
        while($pubs=$pub->fetch()) {
            $id_point_journalier = $pubs['identifiant'];
        }
        
            $req1=$db->prepare('SELECT prix_boisson.*, boisson.nom, boisson.qte_stock, boisson.id AS boisson_id FROM prix_boisson, boisson WHERE boisson.id=prix_boisson.boisson AND prix_boisson.id=?');
            $req1->execute(array($prix_boisson));
            while ($req1s=$req1->fetch()) {
                $prix=$req1s['prix_vente'];
                $qte_stock=$req1s['qte_stock'];
                $benefice=$req1s['benefice'];
                $boisson_id=$req1s['boisson_id'];
                $total=$prix*$qte;
                $tbenefice=$benefice*$qte;
                $des=$req1s['nom'].' '.$req1s['designation'];
                
            }
            if ($qte_stock < $qte) {
                // La quantité en stock est inférieure à celle voulue
                echo (json_encode(['response' => -1]));
            } else {
                $insert=$db->prepare('INSERT INTO table_invoice_details(num_cmd,prix_boisson, designation,qte,price, total,tbenefice,order_date,order_time,id_point_journalier) VALUES(?,?,?,?,?,?,?,?,?,?)');
                $insert->execute(array($num_cmd, $prix_boisson, $des, $qte, $prix, $total, $tbenefice, date('Y-m-d'), date('H:i:s'),$id_point_journalier));

                $red=$db->prepare('UPDATE boisson SET qte_stock=qte_stock-? WHERE id=?');
                $red->execute(array($qte, $boisson_id));

                if ($insert && $red) {
                    //success
                    echo (json_encode(['total' => $total]));
                } else {
                    // erreur
                    echo (json_encode(['total' => 0]));
                }
                
            }


        
 