<?php
// cms/api/preferences/saverates

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'currencies','rates');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $currencies = mysqli_real_escape_string($db, $_GET['currencies']);
    $rates = mysqli_real_escape_string($db, $_GET['rates']);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 56))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    //Partimos los datos
    $currenciesarr = explode('-',$currencies);
    $ratesarr = explode('-',$rates);
    
    if(count($ratesarr) != count($currenciesarr)){
        badEnd('400',array('msg'=>'Parametros invalidos'));
    }
    
    //Recorremos los ids
    foreach($currenciesarr as $index => $currencyid){
        //Recorremos los rates
        foreach($ratesarr as $indextwo => $rate){
            
            // SI el indice coincide lo ingresamos
            if($index == $indextwo){
                //Consultamos el id para saber si existe
                $sql = "SELECT COUNT(currencyid) AS qty ".
                "       FROM cmsprefrates ".
                "       WHERE currencyid = ".$currencyid;
                if (!$rs=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                        
                $row = $rs->fetch_assoc();
                    
                //SI es igual a 0 no existe
                if($row['qty'] == 0){
                    badEnd('204',array('msg'=>'Registro no encontrado'));
                }
                
                // Actualizamos el rate
                $sql = "UPDATE cmsprefrates SET ".
                "       rate = ".$rate.
                "       WHERE currencyid = ".$currencyid;
                if (!$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                if($currencyid != 1){
                    // Obtenemos la el precio en VES
                    $sql = "SELECT rate FROM cmsprefrates WHERE currencyid = 1";
                    if (!$rs = $db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    $row = $rs->fetch_assoc();
                    
                    $sql = "SELECT decimals FROM currencies WHERE id = 1";
                    if (!$res = $db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    $currencydata = $res->fetch_assoc();

                    // Hacemos el rate
                    $ratecal = (1 / $rate) * $row['rate'];
                    
                    $sql = "INSERT INTO rateshistory(createddate, currencyid, amount)".
                    "       VALUES (NOW(), ".$currencyid.", '".number_format($ratecal, $currencydata['decimals'], '.', '')."')";
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                } else {
                    // Actualizamos todos los rates
                    // Obtenemos todos los rates
                    $sql = "SELECT rate, currencyid FROM cmsprefrates WHERE currencyid != 1 AND currencyid > 0";
                    if (!$rs = $db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    while($row = $rs->fetch_assoc()){
                        $ratecal = 0;
                        // Obtenemos el decimal de la moneda
                        $sql = "SELECT decimals FROM currencies WHERE id = ".$row['currencyid'];
                        if (!$res = $db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                        
                        $currencydata = $res->fetch_assoc();
                        
                        // Hacemos el rate
                        $ratecal = (1 / $row['rate']) * $rate;
                        
                        $sql = "INSERT INTO rateshistory(createddate, currencyid, amount)".
                        "       VALUES (NOW(), ".$row['currencyid'].", '".number_format($ratecal, $currencydata['decimals'], '.', '')."')";
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                    }
                }
                
                //COnsultamos el nombre de la moneda para mostrarlo en la auditoria
                $sql = "SELECT name FROM currencies WHERE id = ".$currencyid;
                if (!$rs=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $row = $rs->fetch_assoc();
            
                //auditoria
                setAudit($db, "PREFERENCIAS", $sessionid, "CMS", "Se actualizó la tasa de la moneda ".$row['name']);   
            }
        }
    }
    
    $out->ids = $currencies;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
