<?php
    include_once 'opendb.php';
    $mess="OK";
    $upderrors="None";
    if (isset($_POST["data"]))
    {
        $content=$_POST["data"];
        $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
        $xml=simplexml_load_string($content) or die("Error: Cannot create object");
        foreach ($xml as $Record){
            $CompID= $Record->CompID;
            $pcode = $Record->prod_code;
            $barcode = $Record->barcode;
            $pack_qty = $Record->pack_qty;
            $unit = $Record->uom;
            $pc_unit_id= $Record->pc_unit_id;
            $price1 = $Record->price1;
            $price2 = $Record->price2;
            $price3 = $Record->price3;
            $inactive = $Record->inactive;
            $sql = "SELECT * FROM uom_prices WHERE prod_code like '$pcode' and pc_unit_id = $pc_unit_id and comp_id=$CompID";
         
            $result = $conn->query($sql);
            if ($result->num_rows == 0 ) {
                   $sql = "INSERT INTO uom_prices (prod_code,comp_id,pc_unit_id) VALUES ('$pcode',$CompID,$pc_unit_id)";
                   if ($conn->query($sql) === TRUE)
                   {
                      $mess="OK";
                   } else
                   {
                      $mess= "Error: " . $sql . "<br>" . $conn->error;
                      $upderrors.="Error: " . $sql . "<br>" . $conn->error;
                   } 
                  
                  
            }
            
            if ($mess=="OK")
            {
                $sql = "UPDATE uom_prices SET uom='$unit',"
                                            ."barcode='$barcode',"
                                            ."pack_qty=$pack_qty,"
                                            ."inactive=$inactive,"
					                        ."price1=$price1,"
                                            ."price2=$price2,"
                                            ."price3=$price3,"
                                            ."edit_time=now()"
                                            ." WHERE prod_code like '$pcode' and pc_unit_id=$pc_unit_id and comp_id=$CompID";

                if ($conn->query($sql) === TRUE) {
                    $mess="OK";
                } else {
                    $mess= "Error updating units record: " . $conn->error;
                     $upderrors.="Error updating units record:<br>" . $conn->error.$sql;
                }
                    
            }
        }
        if ($upderrors=="None"){
           echo $mess;
        }
        else {
             echo $upderrors;            
        }
            
            
    }
    else
    {
        echo "ERROR: No data!";
    }
    $conn->close();
?>