<?php
// cms/api/preferences/savepagomovil
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'currencyid', 'depositsbankinterface', 'withdrawalsbankinterface');
    if (!parametrosValidos($_POST, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $out->update = false;
    $sessionid = $_POST['sessionid'];
    $currencyid = mysqli_real_escape_string($db, $_POST['currencyid']);
    $depositsbankinterface = mysqli_real_escape_string($db, $_POST['depositsbankinterface']);
    $withdrawalsbankinterface = mysqli_real_escape_string($db, $_POST['withdrawalsbankinterface']);
    
    //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"));
    
    // Validamos que la moneda exista
    $sql = "SELECT COUNT(id) AS qty ".
    "       FROM currencies".
    "       WHERE id = ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    if ($row['qty'] == 0) {
        badEnd("403", array("msg"=>"Moneda no encontrada"));
    }
    
    // Consultamos los bancos pa ve
    $sql = "SELECT pagomovilbanks, pagomovildefaults ".
    "       FROM cmspreferences";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Nos traemos los objetos
    $banks = json_decode($row['pagomovilbanks'], true);
    $banks = $banks['banks'];
    $default = json_decode($row['pagomovildefaults'], true);
    $default = $default['default'];
    
    // Validamos que las interfaces sean 
    // hacemos un arreglos con los IDS
    $banksIds = [0];
    foreach($banks as $bank){
        $banksIds [] = $bank['id'];
    }
    
    // Validamos que ambas interface existan
    if (!in_array($depositsbankinterface, $banksIds) || !in_array($withdrawalsbankinterface, $banksIds)) {
        badEnd("408", array("msg"=>"Interfaces deben ser ".implode(", ", $banksIds)));
    }
    
    // Validamos, si la moneda existe, ajustamos el objeto, si no, insertamos el nuevo currency
    $currencyexist = false;
    foreach($default as $def){
        if ($def['currency']['id'] == $currencyid) {
            $currencyexist = true;
        }
    }

    // Si existe, modificamos su objeto
    $defaultTmp = [];
    if($currencyexist){
        foreach($default as $def){
            if ($def['currency']['id'] == $currencyid) {
                $def['withdrawals'] = (int) $withdrawalsbankinterface;
                $def['deposits'] = (int) $depositsbankinterface;
            }
            
            $defaultTmp [] = $def;
        }
    }else{
        // Si no existe, agregamos un nuevo item
        $defaultTmp = $default;
        // consultamos el nombre de la moneda
        $sql = "SELECT name, id ".
        "       FROM currencies ".
        "       WHERE id = ".$currencyid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        
        // Creamos el nuevo item
        $defaultItem = new stdClass();
        
        $defaultItem->currency = new stdClass();
        $defaultItem->currency->id = (int) $row['id'];
        $defaultItem->currency->name = $row['name'];
        
        $defaultItem->deposits = (int) $depositsbankinterface;
        $defaultItem->withdrawals = (int) $withdrawalsbankinterface;
        
        $defaultTmp [] = $defaultItem;
    }
    
    $insertedDefault = new stdClass();
    $insertedDefault->default = $defaultTmp;

    //Se enciende la que se envía
    $sql = "UPDATE cmspreferences SET ".
    "       pagomovildefaults = '".json_encode($insertedDefault, JSON_UNESCAPED_UNICODE )."'";
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Retornamos si no se actualizo ningun registro
    if ($db->affected_rows > 0)
        $out->update = true;
    
    //auditoria
    setAudit($db, "PREFERENCIAS", $sessionid, "CMS", "Se actualizaron las preferencias de Pago Movil"); 
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
