'token'])); $action = $_GET['action'] ?? ''; $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"); try { $db->exec("CREATE TABLE IF NOT EXISTS email_templates (id SERIAL PRIMARY KEY, name TEXT NOT NULL, category TEXT DEFAULT 'custom', html_content TEXT, json_content TEXT, thumbnail TEXT, created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW())"); } catch (Exception $e) {} switch ($action) { case 'list': $tpls = []; foreach ($db->query("SELECT id, name, category, LEFT(COALESCE(html_content,html), 100) as preview, created_at FROM email_templates ORDER BY updated_at DESC LIMIT 50") as $r) $tpls[] = $r; echo json_encode(['ok'=>1, 'templates'=>$tpls]); break; case 'save': if ($_SERVER['REQUEST_METHOD'] !== 'POST') die(json_encode(['error'=>'POST'])); $data = json_decode(file_get_contents('php://input'), true); $name = $data['name'] ?? 'Untitled'; $html = $data['html'] ?? ''; $json_data = $data['json'] ?? ''; $category = $data['category'] ?? 'custom'; $id = $data['id'] ?? null; if ($id) { $db->prepare("UPDATE email_templates SET name = ?, html_content = ?, json_content = ?, category = ?, updated_at = NOW() WHERE id = ?") ->execute([$name, $html, $json_data, $category, $id]); } else { $db->prepare("INSERT INTO email_templates (name, html_content, json_content, category) VALUES (?, ?, ?, ?)") ->execute([$name, $html, $json_data, $category]); $id = $db->lastInsertId(); } echo json_encode(['ok'=>1, 'id'=>$id]); break; case 'get': $id = intval($_GET['id'] ?? 0); $tpl = $db->query("SELECT * FROM email_templates WHERE id = $id")->fetch(PDO::FETCH_ASSOC); echo json_encode(['ok'=>1, 'template'=>$tpl]); break; case 'delete': $id = intval($_GET['id'] ?? 0); $db->prepare("DELETE FROM email_templates WHERE id = ?")->execute([$id]); echo json_encode(['ok'=>1]); break; }