<?php 

// ini_set('display_errors', 1);
// ini_set('display_startup_erros', 1);
// error_reporting(E_ALL); 

include_once(__DIR__."/../config.php"); 

$cs = new cs;


if(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
{
    try {
        
        
        $request = $_POST;

        $rows    = $cs->executeQuery("SELECT vencimento FROM gerenciadores WHERE id = {$request['id']}");

        $rows    = $cs->fetchQuery($rows)[0];

        $request['vencimento'] = (!isset($request['vencimento'])) ? $rows['vencimento'] : $request['vencimento'];

        
        
        if (isset($request['usuario']) && isset($request['ids']) && !empty($request['ids'])) {

            $vencimento = '';
            $status     = '';
            $exp_date   = '';

            $ids = $request['ids'];  
            foreach ($ids as $value) {
                
                
                if (isset($request['vencimento']) && !empty($request['vencimento'])) {
                    // $vencimento = new DateTime($request['vencimento']);
                    $vencimento = date('Ymd', strtotime($request['vencimento']));
                    $exp_date   = strtotime($request['vencimento']); 
                    $status     = 0;
                     
                    
                } else {
                    $vencimento = 0;
                    $exp_date   = 0;
                    $status     = 1;  
                } 
                
                $cs->executeQuery("CALL sp_users_update('{$value}', '{$status}', '{$exp_date}', '{$vencimento}')");  
                

            }
            
        } else {
            
            

            $id         = $cs->filterKey($request['id']);
            $nome       = $cs->filterKey($request['nome']);
            $login      = $cs->filterKey($request['login']); 
            $senha      = $cs->filterKey($request['senha']);
            $email      = $cs->filterKey($request['email']);
            $celular    = $cs->returnNumbers($request['celular']);
            $profile    = $cs->filterKey($request['profile']);
            $max_conn   = (isset($request['max_connections'])) ? $cs->filterKey($request['max_connections']) : 1;
            $obs        = $cs->filterKey($request['obs']);
            
            $vencimento = (isset($request['activeClient'])) ? date('Y-m-d H:i:s', strtotime('+1 month')) : date('Y-m-d', strtotime($request['vencimento']));
            
            $exp_date   = strtotime($request['vencimento']); 
            
            $profile_id = $cs->fetchQuery($cs->executeQuery("SELECT id_bouq FROM profiles WHERE profile = '{$profile}'")); 

            $profile_id = json_encode([ (int)$profile_id[0]['id_bouq'] ]);

            $status     = (in_array($cs->filterKey($request['status']), ["teste", "normal"])) ? 'normal': 'desativado';
            $enabled    = (in_array($cs->filterKey($request['status']), ["teste", "normal"])) ? 1 : 0;          
            
            $iptv = "
                UPDATE 
                    usuarios 
                SET 
                    status='{$status}', observacao='{$obs}', display_name='{$nome}',
                    senha='{$senha}', celular='{$celular}', email='{$email}', 
                    profile='{$profile}', vencimento='{$vencimento}', 
                    max_con = '{$max_conn}' 
                WHERE 
                    id='{$id}'";
            
            $cs->executeQuery($iptv); 
            
            $sql = new Sql();

            $res = $sql->query("UPDATE xtream_iptvpro.users SET bouquet = :profile_id, enabled = :enabled, max_connections = :max_conn, exp_date = :exp_date, password = :password WHERE username = :login", [
                ':profile_id' => $profile_id,
                ':enabled'    => $enabled,
                ':max_conn'   => $max_conn,
                ':exp_date'   => $exp_date,
                ':password'   => $senha, 
                ':login'      => $login,              
            ]);
              
            
            echo json_encode([ 
                'success' => true, 
                'class'   => 'alert-success', 
                'text'    => 'Atualizado com sucesso!',
                'data'    => $id
            ]); 
        }      

    } catch (Exception $e) {

        echo json_encode([ 
            'success'=> false, 
            'class'=> 'alert-danger', 
            'text'=> 'Erro ao atualizar!',
            'data' => $e->getMessage() .' - '. $cs->errors 
        ]);
	    
    }    
       

    
}

?>