<?php

/*
|--------------------------------------------------------------------------
| CONFIGURACION VICIDIAL / ASTERISK
|--------------------------------------------------------------------------
*/

// Leer configuración desde BD (settings_telefonia)
global $conn;

$vici_url    = 'http://192.168.40.13';
$vici_user   = '6666';
$vici_pass   = 'Alexa1810';
$vici_source = 'crm';

// Intentar leer desde system_settings si existe
if(isset($conn)){
    $row = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key='vicidial_url' LIMIT 1");
    if($row && $row->num_rows > 0) $vici_url = $row->fetch_assoc()['setting_value'];

    $row = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key='vicidial_user' LIMIT 1");
    if($row && $row->num_rows > 0) $vici_user = $row->fetch_assoc()['setting_value'];

    $row = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key='vicidial_pass' LIMIT 1");
    if($row && $row->num_rows > 0) $vici_pass = $row->fetch_assoc()['setting_value'];
}

define('VICI_URL',    $vici_url);
define('VICI_USER',   $vici_user);
define('VICI_PASS',   $vici_pass);
define('VICI_SOURCE', $vici_source);

define('VICI_DEFAULT_CAMPAIGN', 'ENERGIA_');
define('VICI_DEFAULT_LIST',     '998');

/*
|--------------------------------------------------------------------------
| FUNCION BASE: LLAMAR A LA API DE VICIDIAL
|--------------------------------------------------------------------------
*/

function vicidial_api(array $params, bool $non_agent = false): array
{
    $endpoint = $non_agent
        ? VICI_URL . '/vicidial/non_agent_api.php'
        : VICI_URL . '/agc/api.php';

    $params['source'] = VICI_SOURCE;
    $params['user']   = VICI_USER;
    $params['pass']   = VICI_PASS;

    $url = $endpoint . '?' . http_build_query($params);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $error    = curl_error($ch);
    curl_close($ch);

    if($error){
        return ['success' => false, 'error' => $error];
    }

    return ['success' => true, 'response' => trim($response)];
}