<?php
include_once("utiles.php");

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
date_default_timezone_set("America/Panama");

if (!$connection = connectDb()) {
    die("err db");
} else {
    $connection->query("SET NAMES 'utf8';");
}
header('content-type: application/json');
session_start();
$_SESSION['database'] = $_POST['database'];
$_SESSION['op_id_fin'] = $_POST['op_id_fin'];
$_SESSION['op_id_esp'] = $_POST['op_id_esp'];
$_SESSION['origcarga'] = $_POST['origcarga'];

$cDatabaseN = $_SESSION['database'];
$cOp_id_fin = $_SESSION['op_id_fin'];
$cOp_id_esp = $_SESSION['op_id_esp'];
$cOrigcarga = $_SESSION['origcarga'];
$i_Log = 0;

$hoynow = getdate();

$cmdg_upd1  = "UPDATE " . $cDatabaseN . ".operacion_match_p SET op_id_orig=" . $cOp_id_fin . " WHERE (op_id_orig=" . $cOp_id_esp . ")";
$resp_upd1 = mysqli_query($connection, $cmdg_upd1);
if ($i_Log == 1) {
    echo $cmdg_upd1 . ($resp_upd1 ? ' ->OK' : ' ->FAIL') . chr(13);
    printf("Affected rows: %d\n", $resp_upd2->affected_rows);
}
if ($cOrigcarga = 1) {
    $cmdg_upd2  = "UPDATE " . $cDatabaseN . ".producto_op SET po_cant_pend=po_cant WHERE (po_op_id=" . $cOp_id_fin . ")";
    $resp_upd2 = mysqli_query($connection, $cmdg_upd2);
    if ($i_Log == 1) {
        echo $cmdg_upd2 . ($resp_upd2 ? ' ->OK' : ' ->FAIL') . chr(13);
        printf("Affected rows: %d\n", $resp_upd2->affected_rows);
    }

    $cmdg_upd3 = "UPDATE " . $cDatabaseN . ".producto_op2 SET po_cant_pend=po_cant WHERE (po_op_id=" . $cOp_id_fin . ")";
    $resp_upd3 = mysqli_query($connection, $cmdg_upd3);
    if ($i_Log == 1) {
        echo $cmdg_upd3 . ($resp_upd3 ? ' ->OK' : ' ->FAIL') . chr(13);
        printf("Affected rows: %d\n", $resp_upd3->affected_rows);
    }
}

proc_productos_pend($connection, $cDatabaseN, $cOp_id_fin, $i_Log);

$recount = 0;
$cSql_Cmd = "
    SELECT 
        m.op_id_aplic,
        SUM(p.po_cant_pend) AS suma 
    FROM " . $cDatabaseN . ".operacion_match_p m LEFT OUTER JOIN " . $cDatabaseN . ".producto_op p ON (m.op_id_aplic=p.po_op_id) 
    WHERE  (m.op_id_orig=" . $cOp_id_fin . ")  
    GROUP BY m.op_id_aplic ";
$oQry_Total = getRowAll($connection, $cSql_Cmd, $recount, false);
if ($i_Log == 1) {
    echo $cSql_Cmd . ($oQry_Total ? ' ->OK' : ' ->FAIL') . chr(13);
    echo 'registros: ->' . $recount . chr(13);
}
$resp_upd4 = true;
$resp_upd5 = true;
foreach ($oQry_Total as $row) {
    if ($i_Log == 1) {
        print_r($row);
    }

    if ( round($row['suma'], 2) == 0.00) {

        $cmdg_upd4  = "UPDATE  " . $cDatabaseN . ".operacion SET id_status='1' WHERE op_id=" . $row['op_id_aplic'];
        $resp_upd4 = mysqli_query($connection, $cmdg_upd4);
        if ($i_Log == 1) {
            echo $cmdg_upd4 . ($resp_upd4 ? ' ->OK' : ' ->FAIL') . chr(13);
            printf("Affected rows: %d\n", $resp_upd4->affected_rows);
        }

        $cmdg_upd5  = "UPDATE  " . $cDatabaseN . ".operacion2 SET id_status='1' WHERE op_id=" . $row['op_id_aplic'];
        $resp_upd5 = mysqli_query($connection, $cmdg_upd5);
        if ($i_Log == 1) {
            echo $cmdg_upd5 . ($resp_upd5 ? ' ->OK' : ' ->FAIL') . chr(13);
            printf("Affected rows: %d\n", $resp_upd5->affected_rows);
        }
    }
}
if ($resp_upd1 and $resp_upd2 and $resp_upd3 and $resp_upd4 and $resp_upd5) {
    mysqli_query($connection, "COMMIT");
    $msg = array(
        "success" => "true",
        "detalle" => "OK"
    );
} else {
    mysqli_query($connection, "ROLLBACK");
    $msg = array(
        "success" => "false",
        "detalle" => $connection
    );
    echo "Error: " . $connection->error;
}

print_r(json_encode($msg));

@mysqli_close($connection);

function proc_productos_pend($connection, $cDatabaseN, $cOp_id_fin, $i_Log)
{
    if ($i_Log == 1) {
        echo 'in -> call proc_productos_pend($connection,' . $cDatabaseN . ',' . $cOp_id_fin . ',' . $i_Log . ')' . chr(13);
    }
    $regs1 = 0;
    $cSql_Cmd = "
    SELECT 
        po_id_prod,
        po_cant 
        FROM " . $cDatabaseN . ".producto_op 
        WHERE (po_op_id=" . $cOp_id_fin . ") 
        GROUP BY po_id_prod asc";
    $oQry_Po = getRowAll($connection, $cSql_Cmd, $regs1, false);
    if ($i_Log == 1) {
        echo $cSql_Cmd . ($oQry_Po ? ' ->OK' : ' ->FAIL') . chr(13);
        echo 'registros: ->' . $regs1 . chr(13);
    }

    $regs2 = 0;
    $cSql_Cmd = "
    SELECT 
        op_id_orig,
        op_id_aplic 
    FROM " . $cDatabaseN . ".operacion_match_p 
    WHERE (op_id_orig=" . $cOp_id_fin . ")";
    $oQry_Ma = getRowAll($connection, $cSql_Cmd, $regs2, false);
    if ($i_Log == 1) {
        echo $cSql_Cmd . ($oQry_Ma ? ' ->OK' : ' ->FAIL') . chr(13);
        echo 'registros: ->' . $regs2 . chr(13);
    }

    if ($regs2 = 0) {
        exit;
    }

    foreach ($oQry_Po as $row_po) {
        $po_pr_id = $row_po['po_id_prod'];
        $po_canti = $row_po['po_cant'];

        foreach ($oQry_Ma as $row_ma) {
            $mat_id_orig = $row_ma['op_id_orig'];
            $mat_id_apli = $row_ma['op_id_aplic'];

            $regs3 = 0;
            $cSql_Cmd = "
            SELECT 
                po_id,
                po_id_prod,
                po_cant_pend ,
                po_dep_id 
            FROM " . $cDatabaseN . ".producto_op 
            WHERE (po_cant_pend>0) 
            AND   (po_op_id    =" . $mat_id_apli  . ") 
            AND   (po_id_prod  =" . $po_pr_id . ")";
            $oQry_No = getRowAll($connection, $cSql_Cmd, $regs3, false);
            if ($i_Log == 1) {
                echo $cSql_Cmd . ($oQry_No ? ' ->OK' : ' ->FAIL') . chr(13);
                echo 'registros: ->' . $regs3 . chr(13);
            }

            foreach ($oQry_No as $row_no) {
                $not_po_id = $row_no['po_id'];
                $not_id_prod = $row_no['po_id_prod'];
                $not_cant_pend = $row_no['po_cant_pend'];
                $not_dep_id = $row_no['po_dep_id'];

                if ($not_cant_pend != '') {
                    if ($po_canti > $not_cant_pend) {

                        $cmdg_upd6 =
                            "UPDATE " . $cDatabaseN . ".producto_op SET 
                                po_cant_pend=0 
                            WHERE (po_id       =" . $not_po_id . ")  
                            AND   (po_op_id    =" . $mat_id_apli  . ") 
                            AND   (po_id_prod  =" . $po_pr_id . ")";
                        $resp_upd6 = mysqli_query($connection, $cmdg_upd6);
                        if ($i_Log == 1) {
                            echo $cmdg_upd6 . ($resp_upd6 ? ' ->OK' : ' ->FAIL') . chr(13);
                            printf("Affected rows: %d\n", $resp_upd6->affected_rows);
                        }
                        //actualiza existencia

                        $cmdg_upd7 =
                            "UPDATE  prod_existencia SET 
                                p_existencia = p_existencia+" . $not_cant_pend . " 
                            WHERE (pr_id              =" . $not_id_prod . ") 
                            AND   (p_existencia_dep_id=" . $not_dep_id . ")";
                        $resp_upd7 = mysqli_query($connection, $cmdg_upd7);
                        if ($i_Log == 1) {
                            echo $cmdg_upd7 . ($resp_upd7 ? ' ->OK' : ' ->FAIL') . chr(13);
                            printf("Affected rows: %d\n", $resp_upd7->affected_rows);
                        }
                    } else {
                        $cmdg_upd8 =
                            "UPDATE " . $cDatabaseN . ".producto_op SET 
                                po_cant_pend=(" . $not_cant_pend . "-" . $po_canti . ")
                            WHERE (po_id       =" . $not_po_id . ")  
                            AND   (po_op_id    =" . $mat_id_apli  . ") 
                            AND   (po_id_prod  =" . $po_pr_id . ")";
                        $resp_upd8 = mysqli_query($connection, $cmdg_upd8);
                        if ($i_Log == 1) {
                            echo $cmdg_upd8 . ($resp_upd8 ? ' ->OK' : ' ->FAIL') . chr(13);
                            printf("Affected rows: %d\n", $resp_upd8->affected_rows);
                        }

                        //existencia
                        $cmdg_upd9 =
                            "UPDATE  prod_existencia SET 
                            p_existencia = p_existencia+" . po_canti . " 
                        WHERE (pr_id              =" . $not_id_prod . ") 
                        AND   (p_existencia_dep_id=" . $not_dep_id . ")";
                        $resp_upd9 = mysqli_query($connection, $cmdg_upd9);
                        if ($i_Log == 1) {
                            echo $cmdg_upd9 . ($resp_upd9 ? ' ->OK' : ' ->FAIL') . chr(13);
                            printf("Affected rows: %d\n", $resp_upd9->affected_rows);
                        }
                    }
                }
            }
        }
    }
    if ($i_Log == 1) {
        echo 'exit -> call proc_productos_pend($connection,' . $cDatabaseN . ',' . $cOp_id_fin . ',' . $i_Log . ')' . chr(13);
    }
};

?>