<?php
// Created by Mr. Developer on 13.10.2020
require_once ('connect.php');

$txt = $_POST['txt'];

$array = explode("@", $txt);

$query = mysqli_query($conn, "SET NAMES utf8");

$txt_for_send = "";
$txt_id_qoldiq = "";
$bajarildi = false;

for ($x = 0;$x < count($array);$x++)
{
    if ($array[$x] != "")
    {
        $txt_tovarid_nomi = explode("^", $array[$x]);
        $tovar_id = $txt_tovarid_nomi[0];
        $tovar_soni = $txt_tovarid_nomi[1];

        $query = mysqli_query($conn, "SELECT qoldiq, nomi FROM tovarlar WHERE tovar_id = '$tovar_id' LIMIT 1");

        if ($query !== false && $query->num_rows > 0)
        {
            while ($row = mysqli_fetch_assoc($query))
            {
                $qoldiq = $row['qoldiq'];
                $nomi = $row['nomi'];

                //$qoldiq = str_replace($qoldiq, ' ', '');
                $soni = round($tovar_soni);
                
                if (($qoldiq - $soni) < 0)
                {
                    $txt_for_send = $txt_for_send . " " . $nomi . " товардан заказ сони - " . $soni." та";
                }
                else
                {
                    $qoldiq = $qoldiq - $soni;
                    $txt_id_qoldiq = $txt_id_qoldiq."".$tovar_id."~".$qoldiq."^";
                }
            }
        }
    }
}

if ($txt_for_send == "")
{

    $txt_for_send = "ok";

    $txt_idlar_qoldiqlar = explode("^", $txt_id_qoldiq);

    for ($x = 0;$x < count($txt_idlar_qoldiqlar);$x++)
    {
        if ($txt_idlar_qoldiqlar[$x] != ""){
            $txt = explode("~", $txt_idlar_qoldiqlar[$x]);
            $tovar_id = $txt[0];
            $tovar_soni = $txt[1];
    
            $query = "UPDATE `tovarlar` SET `qoldiq`='$tovar_soni' WHERE tovar_id='$tovar_id' ";
    
            if (mysqli_query($conn, $query))
            { 
                $bajarildi = true; 
            }
            else
            { 
                $bajarildi = false; 
            }
    
        }
    }
}
    echo "".$txt_for_send;

$conn->close();

?>
