'')))); $tags = sanitize_text_field($_POST['tags'] ?? ''); $template_id = (int) ($_POST['template_id'] ?? 0); if (!$template_id) { wp_send_json_error('No category template ID provided.'); } // Save the template ID for next time update_option('inagro_kai_cat_template_id', $template_id); // Parse category HTML → extract filters, groups, cards $importer = new Inagro_KAI_Category_Importer(); try { $content = $importer->parse($html); $elementor_data = $importer->fill_template($content, $template_id); } catch (\Exception $e) { wp_send_json_error('Import failed: ' . $e->getMessage()); } // Derive title from HTML if not provided if (!$title && !empty($content['seo']['title'])) { $title = $content['seo']['title']; } if (!$title) { wp_send_json_error('No title found. Please enter a page title manually.'); } if (!$slug) { $prefix = get_option('inagro_kai_cat_slug_prefix', ''); $slug = $prefix . sanitize_title($title); } // Create the page $post_id = Inagro_KAI_Page_Creator::create( $title, $slug, $elementor_data, $content['seo'] ?? [], $status, $post_type, 0, ['categories' => $categories, 'tags' => $tags] ); if (is_wp_error($post_id)) { wp_send_json_error('Page creation failed: ' . $post_id->get_error_message()); } Inagro_KAI_Page_Creator::log_page([ 'post_id' => $post_id, 'title' => $title, 'topic' => 'Category Import: ' . $title, 'slug' => $slug, 'template_id' => $template_id, 'model' => 'none', 'usage' => [], 'cost_usd' => 0, 'status' => $status, 'created_at' => current_time('mysql'), ]); wp_send_json_success([ 'post_id' => $post_id, 'title' => $title, 'slug' => $slug, 'edit_url' => admin_url("post.php?post={$post_id}&action=elementor"), 'preview_url' => get_permalink($post_id), ]); }); // Export page log as CSV add_action('admin_post_inagro_kai_export_log', function (): void { if (!current_user_can('manage_options')) wp_die('Forbidden', 403); check_admin_referer('inagro_kai_export_log'); $log = get_option('inagro_kai_page_log', []); header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="inagro-kai-log-' . date('Y-m-d') . '.csv"'); $out = fopen('php://output', 'w'); fputcsv($out, ['Date', 'Title', 'Topic', 'Slug', 'Post ID', 'Template ID', 'Model', 'Input Tokens', 'Output Tokens', 'Cost USD', 'Status']); foreach (array_reverse($log) as $row) { fputcsv($out, [ $row['created_at'] ?? '', $row['title'] ?? '', $row['topic'] ?? '', $row['slug'] ?? '', $row['post_id'] ?? '', $row['template_id'] ?? '', $row['model'] ?? '', $row['usage']['input'] ?? '', $row['usage']['output'] ?? '', $row['cost_usd'] ?? '', $row['status'] ?? '', ]); } fclose($out); exit; });