<?php

// ===== CONFIGURACIÓN =====

$espoUrl = 'http://127.0.0.1:8080/api/v1/Lead';

$espoUser = 'admin';
$espoPass = 'Adm1n.Dafelh.2026*';

// =========================

// Recibir datos de Evolution
$input = file_get_contents("php://input");

file_put_contents(
    __DIR__ . '/evolution.log',
    date('Y-m-d H:i:s') . "\n" . $input . "\n\n",
    FILE_APPEND
);

$data = json_decode($input, true);

if (!$data) {
    http_response_code(200);
    exit;
}

/*
Ignorar mensajes enviados por nosotros
*/

if (!empty($data['data']['key']['fromMe'])) {
    exit;
}

/*
Obtener nombre y número
*/

$phone = null;
$name = 'Sin nombre';

if (isset($data['data']['key']['remoteJid'])) {
    $phone = explode('@', $data['data']['key']['remoteJid'])[0];
}

if (!empty($data['data']['pushName'])) {
    $name = $data['data']['pushName'];
}

if (!$phone) {
    http_response_code(200);
    exit;
}

$phoneFormatted = '+' . $phone;

/*
Buscar si ya existe por teléfono
*/

$searchUrl =
    "http://127.0.0.1:8080/api/v1/Lead" .
    "?where[0][type]=equals" .
    "&where[0][attribute]=phoneNumber" .
    "&where[0][value]=" . urlencode($phoneFormatted);

$ch = curl_init($searchUrl);

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => "$espoUser:$espoPass"
]);

$result = curl_exec($ch);

curl_close($ch);

$existing = json_decode($result, true);

if (!empty($existing['total'])) {

    file_put_contents(
        __DIR__ . '/espo.log',
        date('Y-m-d H:i:s') .
        " LEAD YA EXISTE: " .
        $phoneFormatted . "\n",
        FILE_APPEND
    );

    exit;
}

/*
Asignación Round Robin
*/

$asesores = [

    '6a2d9d86b757bba07', // Jose Sanchez
    '6a2ea97e3477effcb', // Josue Vallejo
    '6a2d9cfde2271541d'  // Evelyn Rivera

];

$turnoFile = __DIR__ . '/turno.txt';

if (!file_exists($turnoFile)) {
    file_put_contents($turnoFile, '0');
}

$turno = (int) trim(file_get_contents($turnoFile));

if ($turno >= count($asesores) || $turno < 0) {
    $turno = 0;
}

$assignedUserId = $asesores[$turno];

$nuevoTurno = ($turno + 1) % count($asesores);

file_put_contents($turnoFile, $nuevoTurno);

file_put_contents(
    __DIR__ . '/espo.log',
    date('Y-m-d H:i:s') .
    " TURNO GUARDADO: " . $nuevoTurno .
    " | ASESOR: " . $assignedUserId . "\n",
    FILE_APPEND
);

/*
Crear Lead
*/

$payload = [

    'firstName' => $name,
    'lastName' => '(WhatsApp)',

    'phoneNumber' => $phoneFormatted,

    'assignedUserId' => $assignedUserId

];

$ch = curl_init($espoUrl);

curl_setopt_array($ch, [

    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_USERPWD => "$espoUser:$espoPass",

    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json'
    ],

    CURLOPT_POSTFIELDS => json_encode($payload)

]);

$response = curl_exec($ch);

if ($response === false) {
    file_put_contents(
        __DIR__ . '/espo.log',
        "CURL ERROR: " . curl_error($ch) . "\n",
        FILE_APPEND
    );
}

curl_close($ch);

file_put_contents(

    __DIR__ . '/espo.log',

    date('Y-m-d H:i:s') . "\n" .
    $response . "\n\n",

    FILE_APPEND

);

echo 'OK';
