<?php

$PG_ADDRESS="localhost";
//$PG_ADDRESS="143.208.24.84";
$PG_USER="postgres";
$PG_PASS="caju";
$PG_NAME="erpweb";

// variaveis a serem substituidas

//$empresa = $_POST['empresa'];
//$filial = $_POST['filial'];
//$ano_referencia = $_POST['AnoReferencia'];
$empresa='02';
$filial='01';
// incializa variaveis de totalizacoes
$total_corrente = 0;
$total_referencia = 0;
$diferenca = 0;

date_default_timezone_set('America/Sao_Paulo');

    // configura acesso ao banco de dados
    // conexao com postgres
    $myPDO = 'pgsql:host=' . $PG_ADDRESS . ';port=5432;dbname=' . $PG_NAME . ';user=' . $PG_USER . ';password=' . $PG_PASS;

    $data = date('Y-m-d H:i');
    $ano = substr( $data, 0, 4 );
    $ano_atual = $ano;
    $ano_consulta = intval($ano);
    $ano_referencia = strval($ano_consulta - 1);
    $data_consulta2 = substr($data,0,4) .'-' . substr($data,5,2) .'-' . substr($data,8,2);
    $referencia2 = substr($data,0,4) . substr($data,5,2); // pega mes e ano da data atual
    $referencia_ant2 = $ano_referencia . substr($data,5,2);
    $mes = intval(substr( $data, 5, 2 ));
    $ano_consulta = intval($ano);
 
    if ($mes == 12)
    {
        $mes_ref = '01';
    } else
    {
        $mes++;
        $ano--;
        if (strlen($mes) == 1)
        {
            $mes_ref = '0' . $mes;
        } else
        {
           $mes_ref = $mes;
        }
    } 

    $data_consulta1 = $ano . '-'. $mes_ref . '-' . '01'; 
    $mes_ref_anterior = $mes_ref;
    $referencia1 = $ano . $mes_ref;
    if ($mes_ref_anterior == '01')
    {
       $ano_anterior = strval($ano_consulta - 1);
    } else
    {
        $ano_anterior = strval($ano_consulta - 2);
    }
    $referencia_ant1 = $ano_anterior . $mes_ref;

    $connpg = new PDO($myPDO);
    $retorno = array();
   
    $tipo_nf = 'V';
 
    // total das vendas no periodo
    $sql = "select sum(total) as total from cab_saida where empresa=? and filial=? and referencia between ? and ? and tipo_nf='V'";
    
    $statement3 = $connpg->prepare($sql);
    $statement3->bindParam(1, $empresa);              
    $statement3->bindParam(2, $filial);              
    $statement3->bindParam(3, $referencia1);              
    $statement3->bindParam(4, $referencia2);                  
    $statement3->execute();

    while($results3 = $statement3->fetch(PDO::FETCH_ASSOC))
    {
        $result3[] = $results3;
    }

    $total_corrente = 0;

    foreach($result3 as $row3)
    {
        $total_corrente = $row3['total'];
    }
    
    // pega top 20 cidades
    $sqltcid = "select sum(preco_venda) as venda,view_vendas.nome_cidade as cidade from view_vendas 
                where empresa=? and filial=? and view_vendas.emissao between ? and ? and tipo_nf=?
                group by view_vendas.empresa,view_vendas.filial,cidade order by venda desc limit 10";

    $statementcid = $connpg->prepare($sqltcid);
    $statementcid->bindParam(1, $empresa);              
    $statementcid->bindParam(2, $filial);              
    $statementcid->bindParam(3, $data_consulta1);              
    $statementcid->bindParam(4, $data_consulta2);                  
    $statementcid->bindParam(5, $tipo_nf);              
    $statementcid->execute();

    while($results = $statementcid->fetch(PDO::FETCH_ASSOC))
    {
        $resultcid[] = $results;
    }
    
    // carrega resultado de produtos mais vendidos
    $i = 0;
    foreach($resultcid as $rowtcid)
    {
        $i++;
        $percentual = round($rowtcid['venda']/$total_corrente*100,2); 
        array_push($retorno,array(substr($rowtcid['cidade'],0,35),number_format($rowtcid['venda'],2,',','.'),number_format($percentual,2,',','.')));
        if ($i == 20)
        {
            break;
        }
    }  
    echo json_encode($retorno);
