 <?php

error_reporting(E_ERROR  | E_PARSE);

session_start();
/*
$_SESSION['database'] = $_GET["database"];

$_SESSION['suc_id'] = $_GET["suc_id"];

$_SESSION['est_id'] = $_GET["est_id"];

$_SESSION['id_pack'] =$_GET["id_pack"];
 */

$_SESSION['database'] = $_POST["database"];

$_SESSION['suc_id'] = $_POST["suc_id"];

$_SESSION['est_id'] = $_POST["est_id"];

$_SESSION['id_pack'] = $_POST["id_pack"];

include 'conn.php';

include 'funciones.php';

//logs("xxxxxxxxxxxxxxxxxx");

date_default_timezone_set("America/Panama");

$hoynow = getdate();

//echo print_r($hoynow);

//echo date_default_timezone_get();

$hora = str_pad($hoynow["hours"], 2, "0", STR_PAD_LEFT);

$minutos = str_pad($hoynow["minutes"], 2, "0", STR_PAD_LEFT);

$mes = str_pad($hoynow["mon"], 2, "0", STR_PAD_LEFT);

$dia = str_pad($hoynow["mday"], 2, "0", STR_PAD_LEFT);

$timeStamp = $hoynow["year"] . "-" . $mes . "-" . $dia . " " . $hora . ":" . $minutos . ":" . $hoynow["seconds"];
if ($_SESSION['est_id'] == "0") {
    $SQLupdate = "update " . $_SESSION['database'] . ".sucursales set suc_ult_con='" . $timeStamp . "',suc_pack_prom=" . $_SESSION['id_pack'] . "  where  suc_id='" . $_SESSION['suc_id'] . "' limit 1 ";
} else {
    $SQLupdate = "update " . $_SESSION['database'] . ".estaciones set e_ult_con='" . $timeStamp . "',e_pack_prom=" . $_SESSION['id_pack'] . "  where suc_id='" . $_SESSION['suc_id'] . "'  and e_id='" . $_SESSION['est_id'] . "' limit 1 ";
}

if ($connection->query($SQLupdate) === true) {
    //  echo "update op";
} else {
    echo "Error: " . $SQLupdate . "<br>" . $conn->error;
}

$montoesql1 = "select   id_pack,
			     b.prom_codigo	,
				 b.prom_descrip	,
				 b.prom_suc_id	,
				 b.prom_titem	,
				 b.prom_codigo2	,
				 b.prom_fechai	,
				 b.prom_fechaf	,
				 b.prom_fechain	,
				 b.prom_fechafn	,
				 b.prom_vprecio	,
				 b.prom_vdescu	,

 			   ifnull(	b.prom_fcrea,'2000-01-01')  as prom_fcrea ,
				 b.prom_fmod	,
				 b.prom_inact	,
				 b.syncprocesing	,
				 b.usermodify	,
				 b.useroption	,
				 b.prom_pdescrip	,
				 b.prom_ppreciob	,
				 b.prom_ppreciof	,
				 b.prom_borra	,
				 b.trig_unic,
		 	   ifnull(	b.prom_nfechaf,'0')  as prom_nfechaf ,

               ifnull(	b.cant_rango,'0')  as cant_rango ,



	         ifnull(	b.cant_desde1,'0')  as cant_desde1 ,



	            ifnull(	b.prec_desde1,'0')  as prec_desde1 ,
            ifnull(	b.cant_desde2,'0')  as cant_desde2 ,
	           ifnull(	b.prec_desde2,'0')  as prec_desde2 ,
	             ifnull(	b.cant_desde3,'0')  as cant_desde3 ,
               ifnull(	b.prec_desde3,'0')  as prec_desde3 ,
           ifnull(	b.cant_desde4,'0')  as cant_desde4 ,
             ifnull(	b.prec_desde4,'0')  as prec_desde4 ,
          ifnull(	b.cant_desde5,'0')  as cant_desde5 ,
              ifnull(	b.prec_desde5,'0')  as prec_desde5 ,
              ifnull(	b.cant_desde6,'0')  as cant_desde6 ,
             ifnull(	b.prec_desde6,'0')  as prec_desde6 ,


          	   ifnull(	b.cant_fija,'0')  as cant_fija ,


          	   ifnull(	b.prec_barre,'0')  as prec_barre ,



          	  ifnull(	b.dosxuno,'0')  as dosxuno ,

            ifnull(	b.dosxuno_igual_cod,'0')  as dosxuno_igual_cod ,


            ifnull(	b.cant_l1,'0')  as cant_l1   ,
            ifnull(	b.tipo_l1,'0')  as tipo_l1   ,
             ifnull(	b.cant_l2,'0')  as cant_l2   ,
            ifnull(	b.tipo_l2,'0')  as tipo_l2   ,
            ifnull(	b.dinamica_tipo,'0')  as dinamica_tipo ,

				   ifnull(	b.c_cupon,'0')  as c_cupon,
				   ifnull(  multiplo_de_valor ,'0')  as multiplo_de_valor,
				   ifnull(  multiplo_de_grupo,'0')  as multiplo_de_grupo,

                   ifnull(dlu,'0')  as dlu,
                   ifnull(dma,'0')  as dma,
                   ifnull(dmi,'0')  as dmi,
                   ifnull(dju,'0')  as dju,
                   ifnull(dvi,'0')  as dvi,
                   ifnull(dsa,'0')  as dsa,
                   ifnull(ddo,'0')  as ddo,is_app,app_descripcion



				  from " . $_SESSION['database'] . "_tmp_pack.productos_prom_pack




				 left outer join   " . $_SESSION['database'] . ".productos_prom b on " . $_SESSION['database'] . "_tmp_pack.productos_prom_pack.trig_unic= b.trig_unic



				   where  id_pack='" . $_SESSION['id_pack'] . "' group by b.trig_unic  ";

$qur1 = $connection->query($montoesql1);

$i = 0;

 //echo "prom:". $montoesql1;

//  $jsonData[] ='';

while ($r1 = mysqli_fetch_assoc($qur1)) {

    $jsonTempData = array();
    $jsonTempData['campo1'] = utf8_encode($r1['id_pack']);
    $jsonTempData['campo2'] = utf8_encode($r1['prom_codigo']);
    $jsonTempData['campo3'] = utf8_encode($r1['prom_descrip']);
    $jsonTempData['campo4'] = utf8_encode($r1['prom_suc_id']);
    $jsonTempData['campo5'] = utf8_encode($r1['prom_titem']);
    $jsonTempData['campo6'] = utf8_encode($r1['prom_codigo2']);
    $jsonTempData['campo7'] = utf8_encode($r1['prom_fechai']);
    $jsonTempData['campo8'] = utf8_encode($r1['prom_fechaf']);
    $jsonTempData['campo9'] = utf8_encode($r1['prom_fechain']);
    $jsonTempData['campo10'] = utf8_encode($r1['prom_fechafn']);
    $jsonTempData['campo11'] = utf8_encode($r1['prom_vprecio']);
    $jsonTempData['campo12'] = utf8_encode($r1['prom_vdescu']);
    $jsonTempData['campo13'] = utf8_encode($r1['prom_fcrea']);
    $jsonTempData['campo14'] = utf8_encode($r1['prom_fcrea']);
    $jsonTempData['campo15'] = utf8_encode($r1['prom_inact']);
    $jsonTempData['campo16'] = utf8_encode($r1['syncprocesing']);
    $jsonTempData['campo17'] = "1";
    $jsonTempData['campo18'] = utf8_encode($r1['useroption']);
    $jsonTempData['campo19'] = utf8_encode($r1['prom_pdescrip']);
    $jsonTempData['campo20'] = utf8_encode($r1['prom_ppreciob']);
    $jsonTempData['campo21'] = utf8_encode($r1['prom_ppreciof']);
    $jsonTempData['campo22'] = utf8_encode($r1['prom_borra']);
    $jsonTempData['campo23'] = utf8_encode($r1['trig_unic']);

    $jsonTempData['campo24'] = utf8_encode($r1['prom_nfechaf']);
    $jsonTempData['campo25'] = utf8_encode($r1['cant_rango']);
    $jsonTempData['campo26'] = utf8_encode($r1['cant_desde1']);
    $jsonTempData['campo27'] = utf8_encode($r1['prec_desde1']);
    $jsonTempData['campo28'] = utf8_encode($r1['cant_desde2']);
    $jsonTempData['campo29'] = utf8_encode($r1['prec_desde2']);
    $jsonTempData['campo30'] = utf8_encode($r1['cant_desde3']);
    $jsonTempData['campo31'] = utf8_encode($r1['prec_desde3']);
    $jsonTempData['campo32'] = utf8_encode($r1['cant_desde4']);
    $jsonTempData['campo33'] = utf8_encode($r1['prec_desde4']);
    $jsonTempData['campo34'] = utf8_encode($r1['cant_desde5']);
    $jsonTempData['campo35'] = utf8_encode($r1['prec_desde5']);
    $jsonTempData['campo36'] = utf8_encode($r1['cant_desde6']);
    $jsonTempData['campo37'] = utf8_encode($r1['prec_desde6']);

    $jsonTempData['campo38'] = utf8_encode($r1['cant_fija']);
    $jsonTempData['campo39'] = utf8_encode($r1['prec_barre']);

    $jsonTempData['campo40'] = utf8_encode($r1['dosxuno']);
    $jsonTempData['campo41'] = utf8_encode($r1['dosxuno_igual_cod']);

    $jsonTempData['campo42'] = utf8_encode($r1['cant_l1']);

    $jsonTempData['campo43'] = utf8_encode($r1['tipo_l1']);

    $jsonTempData['campo44'] = utf8_encode($r1['cant_l2']);

    $jsonTempData['campo45'] = utf8_encode($r1['tipo_l2']);

    $jsonTempData['campo46'] = utf8_encode($r1['dinamica_tipo']);

    $jsonTempData['campo47'] = utf8_encode($r1['c_cupon']);

    $jsonTempData['campo48'] = utf8_encode($r1['multiplo_de_valor']);

    $jsonTempData['campo49'] = utf8_encode($r1['multiplo_de_grupo']);

    $jsonTempData['campo50'] = ($r1['dlu']);
    $jsonTempData['campo51'] = ($r1['dma']);
    $jsonTempData['campo52'] = ($r1['dmi']);
    $jsonTempData['campo53'] = ($r1['dju']);
    $jsonTempData['campo54'] = ($r1['dvi']);
    $jsonTempData['campo55'] = ($r1['dsa']);
    $jsonTempData['campo56'] = ($r1['ddo']);

    $jsonTempData['campo57'] = ($r1['is_app']);
    $jsonTempData['campo58'] = ($r1['app_descripcion']);






    $jsonData[] = $jsonTempData;

    $i = $i + 1;
}

$json->registros = $i;

$json->promos = $jsonData;

$hoynow = getdate();

$timeStamp = $hoynow["year"] . "-" . $hoynow["mon"] . "-" . $hoynow["mday"] . " " . $hoynow["hours"] . ":" . $hoynow["minutes"] . ":" . $hoynow["seconds"];

$timeStamp2 = $hoynow["year"] . "-" . $hoynow["mon"] . "-01 00:00:01";
//echo $timeStamp;

$SQLflags = "select idflagprom,timestampdiff(minute ,idflagpromdate,now()) as dif from " . $_SESSION['database'] . ".flag  limit 1";

//    logs($SQLflags);
$qur = $connection->query($SQLflags);

$_SESSION['flags'] = "9";
$_SESSION['dif'] = "1";
while ($r = mysqli_fetch_assoc($qur)) {

    $_SESSION['flags'] = $r['idflagprom'];
    $_SESSION['dif'] = $r['dif'];

    logs("Esta es la diferencias " . $_SESSION['dif']);

}

if ($_SESSION['flags'] == "0" || $_SESSION['dif'] > 4) {

    $SQLupdate44 = "UPDATE " . $_SESSION['database'] . ".flag SET idflagprom=1,idflagpromdate=now() ";

    if ($connection->query($SQLupdate44) === true) {

        logs("Cambio la Bandera prom  a 1 " . $_SESSION['est_id']);

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

    $montoesql3 = "select  " . $_SESSION['database'] . ".productos_prom.prom_codigo as pr_id from " . $_SESSION['database'] . ".productos_prom where usermodify=1  limit 1";

//echo  $montoesql;
    logs($montoesql3);

    $qur = $connection->query($montoesql3);

    $_SESSION['pr_id'] = "NO";

    while ($r = mysqli_fetch_assoc($qur)) {

        $_SESSION['pr_id'] = $r['pr_id'];

    }

    logs('listo prommmmm' . $_SESSION['pr_id']);

    if ($_SESSION['pr_id'] != "NO") {

        $SQLupdate = "UPDATE   " . $_SESSION['database'] . ".productos_prom SET syncprocesing=1,usermodify=0,trig_unic = CONCAT(prom_suc_id,'-',prom_codigo,'-',prom_codigo2) WHERE  usermodify=1  limit 1000";

//echo $SQLupdate;

        logs("uuuuuuuuuuuuuuuuuuuuuuuuuuu" . $SQLupdate);

        if ($connection->query($SQLupdate) === true) {
            //  echo "update op";
        } else {
            echo "Error: " . $SQLupdate . "<br>" . $conn->error;
        }

        if ($_SESSION['est_id'] == "0") {

            $getData = "select suc_corre_eprom+1 as corre_e,suc_id FROM " . $_SESSION['database'] . ".sucursales  where   suc_id=1";
        } else {

            $getData = "select e_corre_eprom+1 as corre_e,e_id FROM " . $_SESSION['database'] . ".estaciones  where   e_id=1 limit 1";
        }

        logs("ccccccccccccccccccccccccccccccc" . $getData);

//$getData = "select * from user";
        $qur = $connection->query($getData);

        $_SESSION['corre'] = 0;

        while ($r = mysqli_fetch_assoc($qur)) {

            $_SESSION['corre'] = $r['corre_e'];
        }

        if ($_SESSION['corre'] > 0) {

            $SQLupdate2 = "  insert into  " . $_SESSION['database'] . "_tmp_pack.productos_prom_pack  (id_pack,trig_unic) select   " . $_SESSION['corre'] . "  as id,
			      	productos_prom.trig_unic


				  from
				 " . $_SESSION['database'] . ".productos_prom


				where productos_prom.syncprocesing=1 limit 1000 ";

            logs($SQLupdate2);

            if ($connection->query($SQLupdate2) === true) {

                $SQLupdate3 = "select id_pack from " . $_SESSION['database'] . "_tmp_pack.productos_prom_pack where  id_pack=" . $_SESSION['corre'] . " limit 1";

                logs('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' . $SQLupdate3);
                $qur = $connection->query($SQLupdate3);

                $empaco = "NO";
                while ($r = mysqli_fetch_assoc($qur)) {

                    $empaco = $r['id_pack'];

                    logs("si consiguio un registro  " . $empaco);

                }

                if ($_SESSION['corre'] == $empaco) {

                    logs("   empaco" . $empaco . " corre  " . $_SESSION['corre']);

                    $SQLupdate4 = "UPDATE " . $_SESSION['database'] . ".productos_prom SET syncprocesing=0,usermodify=0 WHERE   syncprocesing=1 ";

                    logs("   update prom xxxxxxxxxxxxxxxxxxxxxx " . $SQLupdate4);

                    if ($connection->query($SQLupdate4) === true) {

                        $sqlmax = "select max(id_pack) as id_pack from " . $_SESSION['database'] . "_tmp_pack.productos_prom_pack limit 1";

                        $qur12 = $connection->query($sqlmax);

                        $_SESSION['empaco'] = 0;

                        while ($r = mysqli_fetch_assoc($qur12)) {

                            $_SESSION['empaco'] = $r['id_pack'];
                        }

                        if ($_SESSION['est_id'] == "0") {
                            $connection->query("update " . $_SESSION['database'] . ".sucursales set suc_corre_eprom=" . $_SESSION['empaco'] . "");

                            logs("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx update " . $_SESSION['database'] . ".sucursales set suc_corre_eprom=" . $_SESSION['empaco'] . "");

                        } else {

                            $connection->query("update " . $_SESSION['database'] . ".estaciones set e_corre_eprom=" . $_SESSION['empaco'] . "");

                            logs("update " . $_SESSION['database'] . ".estaciones set e_corre_eprom=" . $_SESSION['empaco'] . "");

                        }

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

                } else {
                    echo "Errorde empaque: " . $_SESSION['corre'] . " " . $empaco . "<br>";
                }

            }

        } else {

            //echo "error en busca de corre";

        }

    }

    $SQLupdate44 = "UPDATE " . $_SESSION['database'] . ".flag SET idflagprom=0 ";

    if ($connection->query($SQLupdate44) === true) {

        logs("Cambio la Bandera a 0 " . $_SESSION['est_id']);

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

} else {

    logs("Esta ocupado por la estacionnnnnnnn " . $_SESSION['est_id'] . " Bandera " . $_SESSION['flags']);

}

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

//empacando($_SESSION['database']);

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