<?php
if (!isset($_SERVER["HTTP_HOST"])) {
  //parse_str($argv[1], $_GET);
  parse_str($argv[1], $_POST);
}
session_start();
include "db_connect.php";

$sr_recno = $_POST['sr_recno']; // ok
$arcodigo = $_POST['arcodigo']; //
$qtd_atual = $_POST['qtd_atual']; // ok
$qtd_anterior = $_POST['qtd_anterior'];
$vlr_atual = $_POST['vlr_atual']; // ok
$vlr_anterior = $_POST['vlr_anterior'];
$locacao = $_POST['arlcacao']; // ok
$arcodbar = $_POST['arcodbar']; // ok
$arcodgru = '0001'; //$_POST['arcodgru']; // ok
$arcodvde = "008";
$arnomvde = "JOELMA";
$mac = "F4:3B:D8:6F:64:9A";

if (isset($_POST['arfracio'])) {
    $arfracio = $_POST['arfracio'];
} else {
    $arfracio = 0;
}
/*$arcodvde = $_SESSION['codigo'];
$arnomvde = $_SESSION['nome'];
$mac = $_SESSION['mac'];*/
//$conn->autocommit(false);

try {
    $query = "SELECT CAST( MID( arqtdest, ( artabatu - 1) * 9 + 1 , 9 ) * 1 AS DECIMAL( 9,3 ) ) AS arqtdest, CAST( MID( arvrvend, ( artabatu - 1) * 16 + 1 , 16 ) * 1 AS DECIMAL( 16,2 ) ) as arvrvend FROM estoque WHERE sr_recno = $sr_recno FOR UPDATE";

    $res = mysqli_query($conn, $query);
    if (mysqli_num_rows($res) > 0) {
        while ($row = $res->fetch_object()) {
            if (($row->arqtdest == $qtd_anterior) && ($qtd_atual != "")) {
                $query = "UPDATE estoque SET arfracio = $arfracio, qtd_ajuste = $qtd_atual, data_ajuste = current_date, 
		    arqtdest = IF(arqtdest IS NULL, CONCAT(LEFT(RPAD('', 108, '0'), (artabatu - 1) * 9), LPAD(CAST($qtd_atual AS DECIMAL(9, 3)), 9, '0'), MID(RPAD('', 108, '0'), (artabatu * 9) + 1)), 
            CONCAT(LEFT(RPAD(REPLACE(arqtdest, ' ', '0'), 108, '0'), (artabatu - 1) * 9), LPAD(CAST($qtd_atual AS DECIMAL(9, 3)), 9, '0'), MID(RPAD(REPLACE(arqtdest, ' ', '0'), 108, '0'), (artabatu * 9) + 1))
            ), arpdvenv = ' ', arqtd_estok = $qtd_atual, arcodgru = '$arcodgru',";
	    // ), arpdvenv = ' ', arqtd_estok = $qtd_atual, arcodbar = ?, arcodgru = '$arcodgru',";

	    if (($row->arvrvend == $vlr_anterior) && ($vlr_atual != "")) {
                $query .= "arvrvend = IF(arvrvend IS NULL, CONCAT(LEFT(RPAD('', 192, '0'), (artabatu - 1) * 16), LPAD(CAST($vlr_atual AS DECIMAL(16, 2)), 16, '0'), MID(RPAD('', 192, '0'), (artabatu * 16) + 1)), CONCAT(LEFT(RPAD(REPLACE(arvrvend, ' ', '0'), 192, '0'), (artabatu - 1) * 16), LPAD(CAST($vlr_atual AS DECIMAL(16, 2)), 16, '0'), MID(RPAD(REPLACE(arvrvend, ' ', '0'), 192, '0'), (artabatu * 16) + 1))),
                arvr_venda = $vlr_atual, ";
            }

	    $query .= "arlcacao = '$locacao' WHERE sr_recno = $sr_recno";

                //echo $query;die();
                $stmt = mysqli_prepare($conn, $query);
		/*if ($arcodbar == '') {
		    $stmt->bind_param(null);
		} else { 
		    $stmt->bind_param('$arcodbar');	 
		}*/
                mysqli_stmt_execute($stmt);
//                $conn->commit();
                if (mysqli_affected_rows($conn) > 0) {

                    $query = "INSERT INTO estoque_ajuste (arcodigo, saldo_anterior, saldo_atual, usuario, mac_mobile, sr_deleted) VALUE 
                    ('$arcodigo', $qtd_anterior, $qtd_atual, '$arcodvde', '$mac', ' ')";

                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_execute($stmt);
//                    $conn->commit();
                    $error = mysqli_error($conn);
                    $_SESSION['dberror'] = $error;
                    $_SESSION['error'] = false;
                    $_SESSION['msg'] = "Produto $arcodigo alterado com sucesso!";
//                    $conn->autocommit(true);
                    header('Location: produtos.php');
                    exit();
                } else {
                    $error = mysqli_error($conn);
//echo "problema";                    
//print_r($query);
                    $_SESSION['error'] = true;
                    $_SESSION['msg'] = "Produto $arcodigo não alterado!<br>$error";
//                    $conn->autocommit(true);
                    header('Location: produtos.php');
                    exit();
                }
            } else {
                $_SESSION['error'] = true;
                $_SESSION['msg'] = "Produto com estoque anterior alterado";
//                $conn->autocommit(true);
                header('Location: produtos.php');
                exit();
            }
        }
    }
 
} catch (Exception $e) {
//    $conn->rollback();
    $_SESSION['error'] =  true;
    $_SESSION['msg'] = $e;
    header('Location: produtos.php');
//    exit();
    //print_r($e);
}
