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

    $pname = $inputdata['pname'];
    $pcategory = $inputdata['pcategory'];
    $saleprice = $inputdata['saleprice'];
    $prix_achat = $inputdata['prix_achat'];
    $benefice = $saleprice-$prix_achat;
    $pdecription = $inputdata['pdescription'];

    $nbr="";

    
    // verifier si produit existant

    $agence_verif=$db->prepare('SELECT COUNT(pid) AS nbr FROM tbl_product WHERE pname=?');

    $agence_verif->execute(array($pname));

    while($agence_verifs=$agence_verif->fetch()){

        $nbr=$agence_verifs['nbr'];

    }

     if ($nbr == 0) {

        # ajouter

        $user=$db->prepare('INSERT INTO tbl_product (pname,pcategory,saleprice,prix_achat,benefice,pdescription) VALUES(?,?,?,?,?,?)');

        $user->execute(array($pname,$pcategory,$saleprice,$prix_achat,$benefice,$pdescription));

        if ($user) {
                //création agence réussie

                echo (json_encode(['response' => 1]));



        }else{
            // création non réussie

            echo (json_encode(['response' => 0]));

            

        }

     }else {
        // categorie existe déjà

        echo (json_encode(['response' => -1]));

     }





