<?php 
    //cms/api/pairs/update

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'id','basecurrency','refcurrency','status'); 
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $id = $_GET['id'];
    $basecurrency = $_GET['basecurrency'];
    $refcurrency = $_GET['refcurrency'];
    $status = $_GET['status'];
    
    //Validamos la session
    isSessionValidCMS($db, $sessionid);
    
    // SI el id es 0, creamos un par, si no, actualizamos por su id
    if($id == 0){
        
        //Validamos que tenga privilegios para crear
        if (!tienePrivilegio($db, $sessionid, 58))
            badEnd("403", array("msg"=>"No tiene Privilegios"));
        
        // Validamos que no exista un registro con la misma formacion
        $sql = "SELECT COUNT(id) AS qty ".
        "       FROM pairs ".
        "       WHERE (currencyid = ".$basecurrency." AND refcurrencyid = ".$refcurrency.") ".
        "       OR (currencyid = ".$refcurrency." AND refcurrencyid = ".$basecurrency.") ";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $rs->fetch_assoc();
        
        if($row['qty'] > 0){
            badEnd('402',array('msg'=>'Par existente'));
        }
        
        // Agregamos la moneda en los metodos de pago
        $db->autocommit(FALSE);
        
        $sql = "INSERT INTO pairs(".
        "       refcurrencyid, currencyid, status) ".
        "       VALUES(".
        "       ".$basecurrency.",".$refcurrency.", ".$status.
        "       )";
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error.$sql));
        }
        
        $out->id = (int)$db->insert_id;
        
        //Insertamos los datos en el cmspreffees para las comisiones y todo eso
        $sql = "INSERT INTO cmspreffees(".
        "       levelid, currencyid, ".
        "       pairid, usertype, ".
        "       pctfeedeposits, nmlfeedeposits, ".
        "       pctfeewithdrawals, nmlfeewithdrawals, ".
        "       pctfeexfer, nmlfeesxfer, ".
        "       mindeposit, minexchange, ".
        "       minwithdraw, minxfer, ".
        "       maxqtymonthlyopdeposits, ".
        "       maxamountmonthlyopdeposits, ".
        "   	maxqtymonthlyopwithdrawals, ".
        "       maxamountmonthlyopwithdrawals, ".
        "       maxamountmonthlyopxfer, ".
        "       nmlmktfee, pctmktfee, ".
        "       nmllimitfee, pctlimitfee ".
        "       )".
        "       VALUES";
        // Recorremos los tipos de usuario(2)
        for($i = 0; $i < 2; $i++){
            //Recorremos los niveles (3)
            for($j = 0; $j < 3; $j++){
                $sql .= " (".
                "       ".($j+1).", NULL, ".
                "       ".$out->id.", ".($i+1).", ".
                "       0, 0, ".
                "       0, 0, ".
                "       0, 0, ".
                "       0, 0, ".
                "       0, 0, ".
                "       0, ".
                "       0, ".
                "   	0, ".
                "       0, ".
                "       0, ".
                "       0, NULL, ".
                "       0, NULL ".
                "       ),";
            }
        }
        // Eliminamos la ultima coma jeje
        $sql = substr($sql, 0, -1);
        
        // Guardamos las preferencias
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error.$sql));
        }
        
        // Consultamos para usar el nombre en la auditoria
        $sql = "SELECT CONCAT(curr.symbol,'/',currencies.symbol) AS name ".
        "       FROM currencies, pairs par ".
        "       LEFT JOIN currencies curr ON par.refcurrencyid = curr.id".
        "       WHERE currencies.id = par.currencyid ".
        "       AND par.id = ".$out->id;
        if (!$rs=$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error.$sql));
        }
        
        $row = $rs->fetch_assoc();
        
        //auditoria
        setAudit($db, "PARES", $sessionid, "CMS", "Se agregó el par ".$row['name']);
        
        $db->commit();
        $db->close();
        
    }else{
        
        //Validamos que tenga privilegios para actualizar
        if (!tienePrivilegio($db, $sessionid, 59))
            badEnd("403", array("msg"=>"No tiene Privilegios"));
        
        // COnsultamos que el par exista
        $sql = "SELECT COUNT(id) AS qty ".
        "       FROM pairs ".
        "       WHERE id = ".$id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $rs->fetch_assoc();
        
        // Retornamos 204 cuando la busqueda no obtiene resutados
        if($row['qty'] == 0){
            badEnd("204", array("msg"=>"No se encuentra el registro"));
        }
        
        //Consultamos para verificar que no existe un par igual
        $sql = "SELECT count(id) AS qty FROM pairs ".
        "       WHERE id != ".$id.
        "       AND ( (currencyid = ".$basecurrency." AND refcurrencyid = ".$refcurrency.") ".
        "       OR (currencyid = ".$refcurrency." AND refcurrencyid = ".$basecurrency.") )";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $rs->fetch_assoc();
        
        if($row["qty"] > 0){
            badEnd("402", array("msg"=>"Registro duplicado"));
        }
        
        // Actualizamos el registro
        $sql = "UPDATE pairs SET ".
        "       currencyid = ".$refcurrency.", ".
        "       refcurrencyid = ".$basecurrency.", ".
        "       status = ".$status.
        "       WHERE id = ".$id;
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $out->id = (int)$id;
        
        // Consultamos para usar el nombre en la auditoria
        $sql = "SELECT CONCAT(curr.symbol,'/',currencies.symbol) AS name ".
        "       FROM currencies, pairs par ".
        "       LEFT JOIN currencies curr ON par.refcurrencyid = curr.id".
        "       WHERE currencies.id = par.currencyid ".
        "       AND par.id = ".$id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $row = $rs->fetch_assoc();
        
        //auditoria
        setAudit($db, "PARES", $sessionid, "CMS", "Se actualizó el par ".$row['name']);
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>