
<?php
date_default_timezone_set("America/Panama");

header("Content-Type: text/html;charset=utf-8");

session_start();
$_SESSION['name'] = utf8_encode($_POST['datos']);
$database = $_POST['dbname'];
//$_SESSION['suc_id'] = $_POST['suc_id'];
$_SESSION['dbname'] = $_POST['dbname'];

$_SESSION['suc_id'] = $_POST['suc_id'];
$_SESSION['est_id'] = $_POST['est_id'];
$pack = $_POST['pack'];

include 'conn.php';
include 'creaop_tmp.php';

include 'sincro_op.php';

include 'funciones.php';

//$comillas= "\"";

$comillas = "'";

$data = json_decode($_SESSION['name'], true);
//print_r($data);

logs("datajson: " . $_SESSION['name']);

//$json = $data;

//echo json_encode($json);

$json9 = '{"registros":1,"operaciones":[{"op_id":"464000103","op_fecha":"2015-11-03 21:06:18","op_fechav":"2015-11-03 00:00:00.0","op_id_cliente":"1","op_tipo":"2","op_num_corre":"102","op_subtotal":"2.9900","op_itbms":"0.2100","op_total":"3.2000","u_id":"16","op_estacion":"64","op_manejo":"0.00","op_flete":"0.00","op_seguro":"0.00","op_controldoc":"","op_observ":"","op_desc":"0.0000","op_condicion":"Contado","op_subtotalneto":"2.9900","op_costo":"2.4400","op_contado":"3.2000","op_credito":"0.0000","op_efectivo":"3.2000","op_cheque":"0.0000","op_ncheque":"0","id_banco":"0","op_tdebito":"0.0000","op_tcredito":"0.0000","op_ntdebito":"0","op_ntcredito":"0","op_pagado":"5.200","op_vuelto":"2.000","op_diferencia":"0.000000","op_utilidad":"0.5500","op_utilidadporc":"18.400","hora":"00:00:00","emp_imp1":"0.21","emp_imp2":"0.00","emp_imp3":"0.00","no_control":"106","emp_imp0base":"0.0000","emp_imp1base":"2.9900","emp_imp2base":"0.0000","emp_imp3base":"0.0000","suc_id":"4","op_fechas":"2001-01-01 01:01:01.0","op_tcertificado":"0.000","id_status":"1","c_idfiscal2":"","op_num_ncf":"00012317","op_num_rel":"","op_nombre":"CLIENTE CONTADO","emp_imp4":"0.00","emp_imp4base":"0.0000","op_direc":"","op_telf":"","op_num_fact":"0","sale_id":"1","t_id":"0","mon_op":"01","mon_taza_op":"1.000000000","mon_id1":"01","mon_taza_v1":"1.000000000","mon_taza_c1":"1.000000000","mon_id2":"01","mon_taza_v2":"1.000000000","mon_taza_c2":"1.000000000","mon_id3":"01","mon_taza_v3":"1.000000000","mon_taza_c3":"1.000000000","op_forma_6":"0.000","op_forma_7":"0.000","op_forma_8":"0.000","op_fecha_x":"2015-11-02 09:48:56.0","op_tipodesc":"1","conc_id":"0","op_id_espe":"464000137","op_numserie_if":"PPBT110004454","op_num_nco":"012720","mont_letra":"","op_usuario":"","op_num_aptdo":"0.000","op_saldo_ant_aptdo":"0.000","op_pago_aptdo":"0.000","op_saldo_act_aptdo":"0.000","op_ship_to":"0","op_dir_entrega":"","Saldo_Ant":"0.000","Monto_Pago":"0.000","Saldo_Act":"0.000","op_totitems":"90","op_pedido":"103","op_pedido2":"0","op_aptdo_status":"0","op_aptdo_cancel":"2001-01-01 00:00:00.0","op_aptdo_devol":"2001-01-01 00:00:00.0","op_aptdo_factu":"2001-01-01 00:00:00.0","op_aptdo_pagad":"2001-01-01 00:00:00.0","op_num_fis_ec":"","po_id":"311272","po_op_id":"464000103","po_costo":"2.440","po_precio":"2.990","po_itbms":"7.000","po_id_prod":"RWY807-2X","po_cant":"1.00000","po_v_id":"80","po_dep_id":"1","po_pr_tipo":"3","po_visible_grid":"y","po_precioneto":"2.9900","po_desc1":"0.0000","po_desc2":"0.0000","po_utilidad":"0.550","po_utilidad_porc":"18.3950","po_signo":"1.000","po_montoimp":"0.20930","po_dep_id_tras":"","po_preciotmp":"0.00","mesa":"0","silla":"0","ubicacion":"0","po_comisionv":"0.00","po_comisionv_porc":"0.00","po_comisionc":"0.00","po_comisionc_por":"0.00","mod_id_auto":"0","po_father":"0","ubic_enviada":"0","ubic_enviada2":"0","ubic_enviada3":"0","ubic_enviada4":"0","comanda":"","po_comision_tipo":"0","ubic_id":"0","ubic_id2":"0","ubic_id3":"0","ubic_id4":"0","po_pr_detalle":"","po_comp_id":"","po_cant_pend":"0.00000","po_imp_adic":"0.000","po_montoimp_adic":"0.00000","tpo_desc1":"0","tpo_desc2":"0","po_relac_unic":"464000809","po_descripcion":"CHANCLETA PLAST HOMBR","po_posicion":"1","trig_unic":"464000809","e_id":"64","po_flag_despa":"0","po_fech_despa1":"2015-11-03 21:05:45.0","po_fech_despa2":"2014-08-08 00:00:00.0","SyncProcesing":"1","UserModify":"0","UserOption":"0","id_pack":"2686","op_desctm":"0.000","op_desctp":"0.000"}]}


';

$books = $data;

//print_r($books);

$recibidos = $books['registros'];

$i = 0;

if ($connection->query($sql99) === true) {
    //   echo "New TMP created successfully";

//logs("Creando tabla Tmp: ".$sql99);

} else {
    logs("Error: " . $sql99 . "<br>" . $conn->error);
}

$books2 = $books["operaciones"];

foreach ($books2 as $book) {

// '". $book["op_id"]."',
    //'". $book["op_fecha"]."');";

    $strnombre = str_replace("'", "", $book["po_descripcion"]);
    $strop_num_ncf = str_replace("'", "", $book["op_num_ncf"]);

    $strop_nombre = str_replace("'", "", $book["op_nombre"]);

    $strop_direc = str_replace("'", "", $book["op_direc"]);

//$strop_nombre=utf8_decode($strop_nombre);

    logs("insertando nombre: " . $strop_nombre);

    $sql = $sqlinsert . "




'" . $book["op_id"] . "',
'" . $book["op_fecha"] . "',
'" . $book["op_fechav"] . "',
'" . $book["op_id_cliente"] . "',
'" . $book["op_tipo"] . "',
'" . $book["op_num_corre"] . "',
'" . $book["op_subtotal"] . "',
'" . $book["op_itbms"] . "',
'" . $book["op_total"] . "',
'" . $book["u_id"] . "',
'" . $book["op_estacion"] . "',
'" . $book["op_manejo"] . "',
'" . $book["op_flete"] . "',
'" . $book["op_seguro"] . "',
'" . $book["op_controldoc"] . "',
'" . $book["op_observ"] . "',
'" . $book["op_desc"] . "',
'" . $book["op_condicion"] . "',
'" . $book["op_subtotalneto"] . "',
'" . $book["op_costo"] . "',
'" . $book["op_contado"] . "',
'" . $book["op_credito"] . "',
'" . $book["op_efectivo"] . "',
'" . $book["op_cheque"] . "',
'" . $book["op_ncheque"] . "',
'" . $book["id_banco"] . "',
'" . $book["op_tdebito"] . "',
'" . $book["op_tcredito"] . "',
'" . $book["op_ntdebito"] . "',
'" . $book["op_ntcredito"] . "',
'" . $book["op_pagado"] . "',
'" . $book["op_vuelto"] . "',
'" . $book["op_diferencia"] . "',
'" . $book["op_utilidad"] . "',
'" . $book["op_utilidadporc"] . "',
'" . $book["hora"] . "',
'" . $book["emp_imp1"] . "',
'" . $book["emp_imp2"] . "',
'" . $book["emp_imp3"] . "',
'" . $book["no_control"] . "',
'" . $book["emp_imp0base"] . "',
'" . $book["emp_imp1base"] . "',
'" . $book["emp_imp2base"] . "',
'" . $book["emp_imp3base"] . "',
'" . $book["suc_id"] . "',
'" . $book["op_fechas"] . "',
'" . $book["op_tcertificado"] . "',
'" . $book["id_status"] . "',
'" . $book["c_idfiscal2"] . "',
'" . $strop_num_ncf . "',
'" . $book["op_num_rel"] . "',

'" . $strop_nombre . "',
'" . $book["emp_imp4"] . "',
'" . $book["emp_imp4base"] . "',

'" . $strop_direc . "',
'" . $book["op_telf"] . "',
'" . $book["op_num_fact"] . "',
'" . $book["sale_id"] . "',
'" . $book["t_id"] . "',
'" . $book["mon_op"] . "',
'" . $book["mon_taza_op"] . "',
'" . $book["mon_id1"] . "',
'" . $book["mon_taza_v1"] . "',
'" . $book["mon_taza_c1"] . "',
'" . $book["mon_id2"] . "',
'" . $book["mon_taza_v2"] . "',
'" . $book["mon_taza_c2"] . "',
'" . $book["mon_id3"] . "',
'" . $book["mon_taza_v3"] . "',
'" . $book["mon_taza_c3"] . "',
'" . $book["op_forma_6"] . "',
'" . $book["op_forma_7"] . "',
'" . $book["op_forma_8"] . "',
'" . $book["op_fecha_x"] . "',
'" . $book["op_tipodesc"] . "',
'" . $book["conc_id"] . "',
'" . $book["op_id_espe"] . "',
'" . $book["op_numserie_if"] . "',
'" . $book["op_num_nco"] . "',
'" . $book["mont_letra"] . "',
'" . $book["op_usuario"] . "',
'" . $book["op_num_aptdo"] . "',
'" . $book["op_saldo_ant_aptdo"] . "',
'" . $book["op_pago_aptdo"] . "',
'" . $book["op_saldo_act_aptdo"] . "',
'" . $book["op_ship_to"] . "',
'" . $book["op_dir_entrega"] . "',
'" . $book["Saldo_Ant"] . "',
'" . $book["Monto_Pago"] . "',
'" . $book["Saldo_Act"] . "',
'" . $book["op_totitems"] . "',
'" . $book["op_pedido"] . "',
'" . $book["op_pedido2"] . "',
'" . $book["op_aptdo_status"] . "',
'" . $book["op_aptdo_cancel"] . "',
'" . $book["op_aptdo_devol"] . "',
'" . $book["op_aptdo_factu"] . "',
'" . $book["op_aptdo_pagad"] . "',
'" . $book["op_num_fis_ec"] . "',
'" . $book["po_id"] . "',
'" . $book["po_op_id"] . "',
'" . $book["po_costo"] . "',
'" . $book["po_precio"] . "',
'" . $book["po_itbms"] . "',
'" . $book["po_id_prod"] . "',
'" . $book["po_cant"] . "',
'" . $book["po_v_id"] . "',
'" . $book["po_dep_id"] . "',
'" . $book["po_pr_tipo"] . "',
'" . $book["po_visible_grid"] . "',
'" . $book["po_precioneto"] . "',
'" . $book["po_desc1"] . "',
'" . $book["po_desc2"] . "',
'" . $book["po_utilidad"] . "',
'" . $book["po_utilidad_porc"] . "',
'" . $book["po_signo"] . "',
'" . $book["po_montoimp"] . "',
'" . $book["po_dep_id_tras"] . "',
'" . $book["po_preciotmp"] . "',
'" . $book["mesa"] . "',
'" . $book["silla"] . "',
'" . $book["ubicacion"] . "',
'" . $book["po_comisionv"] . "',
'" . $book["po_comisionv_porc"] . "',
'" . $book["po_comisionc"] . "',
'" . $book["po_comisionc_por"] . "',
'" . $book["mod_id_auto"] . "',
'" . $book["po_father"] . "',
'" . $book["ubic_enviada"] . "',
'" . $book["ubic_enviada2"] . "',
'" . $book["ubic_enviada3"] . "',
'" . $book["ubic_enviada4"] . "',
'" . $book["comanda"] . "',
'" . $book["po_comision_tipo"] . "',
'" . $book["ubic_id"] . "',
'" . $book["ubic_id2"] . "',
'" . $book["ubic_id3"] . "',
'" . $book["ubic_id4"] . "',
'" . $book["po_pr_detalle"] . "',
'" . $book["po_comp_id"] . "',
'" . $book["po_cant_pend"] . "',
'" . $book["po_imp_adic"] . "',
'" . $book["po_montoimp_adic"] . "',
'" . $book["tpo_desc1"] . "',
'" . $book["tpo_desc2"] . "',
'" . $book["po_relac_unic"] . "',
" . $comillas . $strnombre . $comillas . ",
'" . $book["po_posicion"] . "',
'" . $book["trig_unic"] . "',
'" . $book["e_id"] . "',
'" . $book["po_flag_despa"] . "',
'" . $book["po_fech_despa1"] . "',
'" . $book["po_fech_despa2"] . "',
'0',
'1',

'" . $book["UserOption"] . "',
'" . $book["id_pack"] . "',
'" . $book["op_desctm"] . "',

'" . $book["op_desctp"] . "',

'" . $book["ci_op_idx"] . "',

'" . $book["op_v_id"] . "',

'" . $book["ci_op_idz"] . "',

'" . $book["op_forma_9"] . "',

'" . $book["op_forma_10"] . "',
'" . $book["op_forma_11"] . "',


'" . $book["op_forma_12"] . "',

'" . $book["op_forma_13"] . "',

'" . $book["op_forma_14"] . "',

'" . $book["op_forma_15"] . "',

'" . $book["op_forma_16"] . "',

'" . $book["op_forma_17"] . "',

'" . $book["op_forma_18"] . "',

'" . $book["op_forma_19"] . "',


'" . $book["op_forma_20"] . "');";

//echo 'sql ' . $sql ."<br>";

//. mysqli_error($sql)

    if ($connection->query($sql)) {

        //logs("insertando en tabla Tmp: ".$sql);

        $msg = array("status" => 1, "msg" => "Your record inserted successfully");

        $i = $i + 1;
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($connection);

        logs("Error: " . $sql . "<br>" . mysqli_error($connection));
    }

}

if ($recibidos == $i) {

    if ($connection->query($sqlop2v2) === true) {
        //    echo "insert op   =".$sqlop2;

//logs("insert op: ". $sqlop2v2);
    } else {
        echo "Error: " . $sqlop1 . "<br>" . $conn->error;

        logs("Error: " . $sqlop1 . "<br>" . $conn->error);
    }

    usleep(200000);

    if ($connection->query($sqlp_op2v2) === true) {
        //    echo "insert prod_op";

//logs("insert prod_op: ". $sqlp_op2v2);

    } else {
        echo "Error: " . $sqlp_op2v2 . "<br>" . $conn->error;
    }

    $sqlp_op3 = "CALL " . $database . ".Sinc_Genexist001ws2('tmp', '" . $database . "', '" . $_SESSION['unico'] . "', '2','0')";

    if ($connection->query($sqlp_op3) === true) {
        //    echo "insert prod_op";

        logs("insert actualiza existencia: " . $sqlp_op3);

    } else {
        echo "Error: " . $sqlp_op3 . "<br>" . $conn->error;
    }

    $sqlp_op3a = "CALL " . $database . ".Sinc_Genexist001ws2('tmp', '" . $database . "', '" . $_SESSION['unico'] . "', '16','0')";

    if ($connection->query($sqlp_op3a) === true) {
        //    echo "insert prod_op";

        logs("insert actualiza existencia: " . $sqlp_op3a);

    } else {
        echo "Error: " . $sqlp_op3a . "<br>" . $conn->error;
    }

//$sqlcorre="update ".$database.".estaciones set e_ftp_rop='".$pack."' where e_id='".$_SESSION['est_id']."'" ;

    if ($_SESSION['est_id'] == "0") {
        logs("Entro por sucursales " . $_SESSION['est_id']);

        $sqlcorre = "update " . $database . ".sucursales set suc_ftp_rop='" . $pack . "' where suc_id='" . $_SESSION['suc_id'] . "'";
    } else {
        logs("Entro por estaciones " . $_SESSION['est_id']);

        $sqlcorre = "update " . $database . ".estaciones set e_ftp_rop='" . $pack . "' where e_id='" . $_SESSION['est_id'] . "' and suc_id='" . $_SESSION['suc_id'] . "'";

    }

    if ($connection->query($sqlcorre) === true) {
        //    echo "update prod_op";

        logs("actualiza corre: " . $sqlcorre);

    } else {
        echo "Error: " . $sqlcorre . "<br>" . $conn->error;
    }

}

//retorno = "{\"estado\":\"OK\",\"mensaje\":\""
//                            + "Oper. enviadas en total: " + registros
//                            + " Procesados: " + acum + "\"}";

$msg = array("estado" => "OK", "mensaje" => "Oper. enviadas en total: " . $recibidos . " Procesados: " . $i);

$json = $msg;

header('content-type: application/json');
echo json_encode($json);

//print_r ($books2);
//access property of object in array
//   foreach ($books2 as $book) {
//   echo 'This book is a ' . $book->op_id . ' Autor:  ' . $book->op_fecha ."<br>";
//}

$qur = null;
@mysqli_close($connection);
?>