<?php
declare(strict_types=1);

/**
 * Helper para tu enviador de mailing.
 *
 * Crea/reutiliza un token real para el destinatario y devuelve sus URLs.
 * Incluye este archivo desde el PHP que prepara el mailing.
 */

function tr_csv_read(string $path): array {
    if (!is_file($path)) return [];
    $fp = fopen($path, 'rb');
    if (!$fp) return [];
    $header = fgetcsv($fp);
    if (!$header) { fclose($fp); return []; }
    $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string)$header[0]);
    $out = [];
    while (($row = fgetcsv($fp)) !== false) {
        if (count($row) !== count($header)) continue;
        $a = array_combine($header, $row);
        if ($a !== false) $out[] = $a;
    }
    fclose($fp);
    return $out;
}

function tr_get_or_create_token(array $lead, string $tokensFile): string {
    $leadId = trim((string)($lead['lead_id'] ?? ''));
    $email = strtolower(trim((string)($lead['email'] ?? '')));
    $referencia = trim((string)($lead['referencia'] ?? ''));

    if ($leadId === '' && $email === '') {
        throw new RuntimeException('El lead necesita lead_id o email.');
    }

    // Reutilizar token del mismo lead + referencia si ya existe.
    foreach (tr_csv_read($tokensFile) as $row) {
        $sameLead = ($leadId !== '' && (string)($row['lead_id'] ?? '') === $leadId)
            || ($email !== '' && strtolower((string)($row['email'] ?? '')) === $email);

        if ($sameLead && (string)($row['referencia'] ?? '') === $referencia && !empty($row['token'])) {
            return (string)$row['token'];
        }
    }

    $token = bin2hex(random_bytes(24));

    $isNew = !is_file($tokensFile) || filesize($tokensFile) === 0;
    $fp = fopen($tokensFile, 'ab');
    if (!$fp) throw new RuntimeException('No se puede escribir tokens_email.csv');

    flock($fp, LOCK_EX);

    if ($isNew) {
        fputcsv($fp, [
            'token','lead_id','nombre','email','telefono',
            'campana','referencia','titulo'
        ]);
    }

    fputcsv($fp, [
        $token,
        $leadId,
        (string)($lead['nombre'] ?? ''),
        $email,
        (string)($lead['telefono'] ?? ''),
        (string)($lead['campana'] ?? ''),
        $referencia,
        (string)($lead['titulo'] ?? '')
    ]);

    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);

    return $token;
}

function tr_action_urls(string $baseUrl, string $token): array {
    $base = rtrim($baseUrl, '?&');
    $t = rawurlencode($token);

    return [
        'me_interesa' => $base . '?t=' . $t . '&a=me_interesa',
        'visita'      => $base . '?t=' . $t . '&a=visita',
        'mas_info'    => $base . '?t=' . $t . '&a=mas_info',
        'no_interesa' => $base . '?t=' . $t . '&a=no_interesa',
    ];
}

/*
EJEMPLO DE USO:

$lead = [
    'lead_id'    => '1832',
    'nombre'     => 'Juan García',
    'email'      => 'juan@example.com',
    'telefono'   => '600000000',
    'campana'    => 'MATCH_SEPTIEMBRE',
    'referencia' => 'AD1721',
    'titulo'     => 'Piso en Playa de San Juan'
];

$tokensFile = __DIR__ . '/private/tokens_email.csv';

$token = tr_get_or_create_token($lead, $tokensFile);

$urls = tr_action_urls(
    'https://mytotalrent.com/email.php',
    $token
);

$html = str_replace(
    [
        '{{NOMBRE}}',
        '{{URL_ME_INTERESA}}',
        '{{URL_VISITA}}',
        '{{URL_MAS_INFO}}',
        '{{URL_NO_INTERESA}}'
    ],
    [
        htmlspecialchars($lead['nombre'], ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($urls['me_interesa'], ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($urls['visita'], ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($urls['mas_info'], ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($urls['no_interesa'], ENT_QUOTES, 'UTF-8')
    ],
    $plantillaEmail
);
*/