<?php
// socialmediamanager/app/tagx.php
// Simple TagX-like extractor: produces meta title/description + tags + snippet suggestions.
require_once __DIR__ . "/db.php";

function smm_tagx_extract(string $title, string $html): array {
  $plain = trim(preg_replace('/\s+/', ' ', strip_tags($html)));
  $plain = preg_replace('/\s+/', ' ', $plain);

  $meta_title = $title;
  if (strlen($meta_title) > 60) $meta_title = substr($meta_title, 0, 57) . "...";

  $meta_desc = $plain;
  if (strlen($meta_desc) > 160) $meta_desc = substr($meta_desc, 0, 157) . "...";

  // very light keyword extraction
  $words = preg_split('/[^a-zA-Z0-9]+/', strtolower($plain));
  $stop = array_flip(["the","and","a","an","to","of","in","on","for","with","is","are","was","were","be","this","that","it","as","at","by","or","from","your","you","we","our","us","but","not","can","will","if","they","their","them"]);
  $freq = [];
  foreach ($words as $w) {
    if ($w === "" || strlen($w) < 4) continue;
    if (isset($stop[$w])) continue;
    $freq[$w] = ($freq[$w] ?? 0) + 1;
  }
  arsort($freq);
  $top = array_slice(array_keys($freq), 0, 12);

  $tags = [];
  foreach ($top as $w) $tags[] = $w;
  $hashtags = array_map(fn($t)=>"#".preg_replace('/[^a-z0-9]/','', $t), array_slice($tags,0,8));

  $snippet = "<meta name=\"description\" content=\"" . htmlspecialchars($meta_desc, ENT_QUOTES) . "\">\n"
           . "<meta property=\"og:title\" content=\"" . htmlspecialchars($meta_title, ENT_QUOTES) . "\">\n"
           . "<meta property=\"og:description\" content=\"" . htmlspecialchars($meta_desc, ENT_QUOTES) . "\">\n";

  return [
    "meta_title"=>$meta_title,
    "meta_description"=>$meta_desc,
    "tags"=>$tags,
    "hashtags"=>$hashtags,
    "meta_snippet"=>$snippet
  ];
}
