<?php
// cms/api/accounting/account
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $out->currency = new stdClass();
    $out->pair = new stdClass();
    $sessionid = $_GET["sessionid"];
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 86))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    $out->currency->types = getCurrencies($db);
    $out->pair->types = getPairs($db);
    
    // Momento crear cuentas
    
    // Buscamos las monedas existentes
    $sql = "SELECT * FROM currencies WHERE id > 0";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    // Recorremos las monedas para validar que existe una cuenta para ella de cada TIPO
    while ($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row['id'];
        $record->name = $row['name'];
        $record->symbol = $row['symbol'];
        
        $accountscurr = [];
        // Recorremos cada categoria
        foreach($out->currency->types as $categories){
            // Dentro de cada categoria recorremos los tipos
            foreach($categories->subtypes as $subtype) {
                if(($categories->id == 24 || $categories->id == 32) && $row['id'] != 1){
                    continue;
                }
                
                // Buscamos una cuenta con esta categoria y esta moneda
                $sql = "SELECT COUNT(acc.id) AS qty ".
                "       from accountingaccounts acc, accountingtypes acctype ".
                "       WHERE acc.currencyid = ".$row['id'].
                "       AND acctype.id = ".$subtype->id.
                "       AND acc.type = acctype.cod";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $accountingExist = $res->fetch_assoc();
                
                // Si no existe, insertamos una cuenta
                if ($accountingExist['qty'] == 0){
                    
                    // Buscamos el cod de la categoria
                    $sql = "SELECT cod FROM accountingtypes WHERE id = ".$subtype->id;
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                        
                    $type = $res->fetch_assoc();
                    
                    $sql = "INSERT INTO accountingaccounts (".
                    "       currencyid, ".
                    "       type, ".
                    "       account ".
                    "       )".
                    "       VALUES ( ".
                    "       '".$row['id']."', ".
                    "       '".$type['cod']."',".
                    "       ''".
                    "       )";
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                }
            }
        }
        
        // Obtenemos las cuentas
        $sql = "SELECT acc.id AS id, ".
        "       acc.account AS account, ".
        "       acctype.id AS typeid, ".
        "       acctype.dsc AS typecategory,".
        "       acctype.cod AS cod ".
        "       FROM accountingaccounts acc, accountingtypes acctype ".
        "       WHERE acc.currencyid = ".$row['id'].
        "       AND acc.type = acctype.cod";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        while($accounting = $res->fetch_assoc()){
            $account = new stdClass();
            
            $account->id = (int)$accounting['id'];
            $account->dsc = $accounting['account'];
            
            $account->subtype = new stdClass();
            $account->subtype->id = (int)$accounting['typeid'];
            $account->subtype->dsc = $accounting['typecategory'];
            $account->subtype->cod = $accounting['cod'];
            
            $accountscurr [] = $account;
        }
        
        $record->accounts = $accountscurr;
        
        $currencies [] = $record;
    }
    
    $out->currency->currencies = $currencies;
    
    // Momento pares
    
    // Obtenemos los pares
    $sql = "SELECT pairs.id AS pairid, ".
    "       CONCAT(".
    "       (SELECT currencies.symbol FROM currencies WHERE currencies.id = pairs.refcurrencyid), ".
    "       '/', ".
    "       (SELECT currencies.symbol FROM currencies WHERE currencies.id = pairs.currencyid)".
    "       ) AS name".
    "       FROM pairs WHERE pairs.id > 0";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    // Recorremos todos los pares para saber si existe o no la cuenta de cada TIPO
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row['pairid'];
        $record->name = $row['name'];
        
        // Obtenemos el nombre del par sin /
        $nameSavedArr = explode('/', $record->name);
        $nameSaved = $nameSavedArr[0].$nameSavedArr[1];
        
        $pairaccount = [];
        // Recorremos cada categoria
        foreach($out->pair->types as $categories){
            // Dentro de cada categoria recorremos los tipos
            foreach($categories->subtypes as $subtype) {
                
                // Buscamos una cuenta con esta categoria y esta moneda
                $sql = "SELECT COUNT(acc.id) AS qty ".
                "       from accountingaccounts acc, accountingtypes acctype ".
                "       WHERE acctype.id = ".$subtype->id.
                "       AND acc.type = CONCAT(acctype.cod, '".$nameSaved."')";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $accountingExist = $res->fetch_assoc();
                
                // Si no existe, insertamos una cuenta
                if ($accountingExist['qty'] == 0){
                    
                    // Buscamos el cod de la categoria
                    $sql = "SELECT cod FROM accountingtypes WHERE id = ".$subtype->id;
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                        
                    $type = $res->fetch_assoc();
                    
                    $sql = "INSERT INTO accountingaccounts (".
                    "       currencyid, ".
                    "       type, ".
                    "       account ".
                    "       )".
                    "       VALUES ( ".
                    "       '', ".
                    "       '".$type['cod'].$nameSaved."',".
                    "       ''".
                    "       )";
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                }
            }
        }
        
        // Obtenemos las cuentas
        $sql = "SELECT acc.id AS id, ".
        "       acc.account AS account, ".
        "       acctype.id AS typeid, ".
        "       acctype.dsc AS typecategory,".
        "       acc.type AS cod ".
        "       FROM accountingaccounts acc, accountingtypes acctype ".
        "       WHERE acc.type = CONCAT(acctype.cod, '".$nameSaved."')";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        while($accounting = $res->fetch_assoc()){
            $account = new stdClass();
            
            $account->id = (int)$accounting['id'];
            $account->dsc = $accounting['account'];
            
            $account->subtype = new stdClass();
            $account->subtype->id = (int)$accounting['typeid'];
            $account->subtype->dsc = $accounting['typecategory'];
            $account->subtype->cod = $accounting['cod'];
            
            $pairaccount [] = $account;
        }
        
        $record->accounts = $pairaccount;
        
        $pairs [] = $record;
    }
    
    $out->pair->pairs = $pairs;
    
    //Retornamos los privilegios del usuario en este modulo
    $access = new stdClass();
    $access->read =   tienePrivilegio($db, $sessionid, 86);
    $access->update = tienePrivilegio($db, $sessionid, 84);
    $out->privileges = $access;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    function getCurrencies($db, $father = 0){
        if ($father==0)
            $sql = "SELECT id, dsc, cod, category ".
            "       FROM accountingtypes ".
            "       WHERE category IS NULL ".
            "       AND cod LIKE '%currency%'".
            "       ORDER BY dsc";
        else
            $sql = "SELECT id, dsc, cod, category ".
            "       FROM accountingtypes ".
            "       WHERE category = ".$father.
            "       ORDER BY dsc";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    
        $records = array();
        
        while ($row = $rs->fetch_assoc()){
            $record = new stdClass();
            $record->id = (int)$row["id"];
            $record->dsc = $row["dsc"];
            
            if ($father == 0){
                $record->subtypes = getCurrencies($db, (int)$row["id"]);  
            }
            
            $records[] = $record;
        }
        
        return $records;
    }
    
    function getPairs($db, $father = 0){
        if ($father==0)
            $sql = "SELECT id, dsc, cod, category ".
            "       FROM accountingtypes ".
            "       WHERE category IS NULL ".
            "       AND cod LIKE '%pair%'".
            "       ORDER BY dsc";
        else
            $sql = "SELECT id, dsc, cod, category ".
            "       FROM accountingtypes ".
            "       WHERE category = ".$father.
            "       ORDER BY dsc";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
    
        $records = array();
        
        while ($row = $rs->fetch_assoc()){
            $record = new stdClass();
            $record->id = (int)$row["id"];
            $record->dsc = $row["dsc"];
            
            if ($father == 0){
                $record->subtypes = getPairs($db, (int)$row["id"]);  
            }
            
            $records[] = $record;
        }
        
        return $records;
    }
?>