Files
html/api/contact-import.php
2026-04-12 22:57:03 +02:00

48 lines
2.2 KiB
PHP

<?php
require_once __DIR__ . '/_secrets.php';
header('Content-Type: application/json');
$token = $_GET['token'] ?? $_POST['token'] ?? '';
if ($token !== 'WEVADS2026') die(json_encode(['error'=>'token']));
$db = new PDO('pgsql:host=10.1.0.3;port=5432;dbname=adx_system','admin',weval_secret('WEVAL_PG_ADMIN_PASS'));
$db->exec("SET search_path TO admin");
$action = $_GET['action'] ?? 'upload';
if ($action === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
$csv_data = $data['csv'] ?? '';
$list_name = $data['list_name'] ?? 'import_' . date('Ymd');
if (!$csv_data) die(json_encode(['error'=>'No CSV data']));
$lines = explode("\n", trim($csv_data));
$header = str_getcsv(array_shift($lines));
$email_col = array_search('email', array_map('strtolower', $header));
$name_col = array_search('name', array_map('strtolower', $header));
$first_col = array_search('first_name', array_map('strtolower', $header));
if ($email_col === false) $email_col = 0;
$imported = 0; $skipped = 0; $invalid = 0;
$st = $db->prepare("INSERT INTO send_contacts (email, first_name, status, source, score) VALUES (?, ?, 'active', ?, 'warm') ON CONFLICT (email) DO NOTHING");
foreach ($lines as $line) {
if (!trim($line)) continue;
$cols = str_getcsv($line);
$email = filter_var($cols[$email_col] ?? '', FILTER_VALIDATE_EMAIL);
if (!$email) { $invalid++; continue; }
$name = $cols[$name_col ?? $first_col ?? 1] ?? '';
try {
$st->execute([$email, $name, $list_name]);
if ($st->rowCount() > 0) $imported++;
else $skipped++;
} catch (Exception $e) { $skipped++; }
}
echo json_encode(['ok'=>1, 'imported'=>$imported, 'skipped'=>$skipped, 'invalid'=>$invalid, 'total_lines'=>count($lines), 'list'=>$list_name]);
} elseif ($action === 'stats') {
$sources = [];
foreach ($db->query("SELECT source, COUNT(*) as cnt FROM send_contacts WHERE source LIKE 'import_%' OR source LIKE 'form_%' GROUP BY source ORDER BY cnt DESC LIMIT 20") as $r) $sources[] = $r;
echo json_encode(['ok'=>1, 'imports'=>$sources]);
}