<?php
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_auth_common.php';
require_once dirname(__DIR__) . '/_trial_service.php';
$trialWhatsappHelper = dirname(dirname(__DIR__)) . '/includes/whatsapp_helper.php';
if (is_file($trialWhatsappHelper)) {
    require_once $trialWhatsappHelper;
}

function trial_whatsapp_schema(PDO $db): void {
    $db->exec("CREATE TABLE IF NOT EXISTS trial_whatsapp_runs (
        run_key TEXT PRIMARY KEY,
        mac TEXT NOT NULL DEFAULT '',
        whatsapp TEXT NOT NULL DEFAULT '',
        status TEXT NOT NULL DEFAULT 'pending',
        error TEXT NOT NULL DEFAULT '',
        created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
        updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))
    )");
}

function trial_notify_whatsapp(PDO $db, array $result, string $macNorm, string $deviceType): array {
    if (($result['status'] ?? '') !== 'success') {
        return ['status' => 'skipped', 'reason' => 'trial_not_created'];
    }
    $dados = is_array($result['dados'] ?? null) ? $result['dados'] : [];
    $whatsapp = preg_replace('/\D+/', '', (string)($dados['whatsapp'] ?? trial_req('whatsapp', ''))) ?: '';
    if ($whatsapp === '') {
        return ['status' => 'skipped', 'reason' => 'whatsapp_empty'];
    }

    trial_whatsapp_schema($db);
    $username = (string)($dados['username'] ?? '');
    $password = (string)($dados['senha'] ?? $dados['password'] ?? '');
    $vencimento = (string)($dados['vencimento'] ?? '');
    $runKey = 'trial_' . hash('sha256', $macNorm . '|' . $whatsapp . '|' . $username . '|' . $vencimento);

    $ins = $db->prepare("INSERT OR IGNORE INTO trial_whatsapp_runs (run_key, mac, whatsapp, status) VALUES (?, ?, ?, 'pending')");
    $ins->execute([$runKey, $macNorm, $whatsapp]);
    if ($ins->rowCount() === 0) {
        return ['status' => 'duplicate', 'run_key' => $runKey];
    }

    $payload = [
        'run_key' => $runKey,
        'phone' => $whatsapp,
        'whatsapp' => $whatsapp,
        'nome' => (string)($dados['nome_cliente'] ?? trial_req('nome', '')),
        'mac' => $macNorm,
        'device_id' => $macNorm,
        'device_type' => $deviceType,
        'username' => $username,
        'password' => $password,
        'dns' => (string)($result['dns_salva'] ?? ''),
        'vencimento' => $vencimento,
        'validade' => $vencimento,
        'link_pagamento' => (string)trial_req('link_pagamento', ''),
    ];

    if (!function_exists('wa_bot_request')) {
        $db->prepare("UPDATE trial_whatsapp_runs SET status='error', error=?, updated_at=strftime('%s','now') WHERE run_key=?")
            ->execute(['chatbot_helper_unavailable', $runKey]);
        return ['status' => 'error', 'run_key' => $runKey, 'message' => 'chatbot_helper_unavailable'];
    }

    $send = wa_bot_request($db, 'POST', '/admin/send-iptv-test', $payload);
    $data = is_array($send['data'] ?? null) ? $send['data'] : [];
    $ok = !empty($send['success']) && (!isset($data['ok']) || !empty($data['ok']));
    $status = !empty($data['sent']) ? 'sent' : (!empty($data['queued']) ? 'queued' : ($ok ? 'sent' : 'error'));
    $error = $ok ? '' : (string)($data['error'] ?? $data['message'] ?? $send['message'] ?? 'chatbot_error');

    $db->prepare("UPDATE trial_whatsapp_runs SET status=?, error=?, updated_at=strftime('%s','now') WHERE run_key=?")
        ->execute([$status, $error, $runKey]);

    return [
        'status' => $status,
        'run_key' => $runKey,
        'message' => $ok ? (string)($data['message'] ?? 'Mensagem enviada ou enfileirada.') : $error,
    ];
}

try {
    ini_set('display_errors', '0');
    error_reporting(E_ALL);
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/db.db', null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_TIMEOUT => 12,
    ]);
    $db->exec('PRAGMA busy_timeout = 12000');
    $db->exec('PRAGMA journal_mode = WAL');
    $db->exec('PRAGMA synchronous = NORMAL');
    $db->exec('PRAGMA temp_store = MEMORY');
} catch (Throwable $e) {
    auth_json_out(['status' => 'error', 'message' => 'db_connection_error']);
}

auth_ensure_schema($db);
$cfg = auth_get_test_config($db);
$flags = auth_get_app_flags($db);
if (!$cfg) {
    auth_json_out(['status' => 'error', 'message' => 'config_not_found']);
}
if ((int)($cfg['enabled'] ?? 0) !== 1 || (int)($flags['test_button_enabled'] ?? 1) !== 1) {
    auth_json_out(['status' => 'disabled', 'message' => 'Teste desativado no painel.']);
}
$mac = $_POST['mac'] ?? $_GET['mac'] ?? trial_req('mac', null);
$macNorm = auth_normalize_mac((string)$mac);
if ($macNorm === '' || strlen(str_replace(':', '', $macNorm)) !== 12) {
    auth_json_out(['status' => 'error', 'message' => 'mac_invalid']);
}
$deviceType = da_normalize_device_type((string)trial_req('device_type', 'tv'));
$result = gerar_teste_service($db, $macNorm, $cfg, ['device_type' => $deviceType]);
if (($result['status'] ?? '') === 'success') {
    try {
        $result['whatsapp_notification'] = trial_notify_whatsapp($db, $result, $macNorm, $deviceType);
    } catch (Throwable $e) {
        $result['whatsapp_notification'] = ['status' => 'error', 'message' => 'chatbot_notification_error'];
    }
}
auth_json_out($result);
