<?php
/**
 * Auto News - Publish endpoint
 * Form submit হলে mahamudfutureit_article table এ insert করে
 */
require_once('config.php');
require_once('inc/NewsScraper.php');

if (empty($_COOKIE['Google_SLKA'])) {
    header("Location:login.php");
    exit;
}

if (!isset($_POST['publish_auto_news'])) {
    header("Location:auto-news.php");
    exit;
}

// Duplicate check by source URL (PostAttachment field used to store source link)
$source_url = trim($_POST['source_url'] ?? '');
if ($source_url) {
    $check = $conn->prepare("SELECT PostId FROM mahamudfutureit_article WHERE PostAttachment = ? LIMIT 1");
    $check->execute([$source_url]);
    if ($check->fetch()) {
        header("Location:auto-news.php?status=duplicate");
        exit;
    }
}

// Date folders for image
$the_year  = date('Y');
$the_month = date('m');
$the_time  = date('Y-m-d H:i:s');

$saved_image = null;
$target_dir = '../uploads/' . $the_year . '/' . $the_month;
if (!is_dir($target_dir)) @mkdir($target_dir, 0755, true);

// Priority 1: uploaded file from computer
if (!empty($_FILES['image_file']['tmp_name']) && is_uploaded_file($_FILES['image_file']['tmp_name'])) {
    $ext = strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','webp','gif'])) $ext = 'jpg';
    $fname = 'AutoNews_' . time() . '_' . mt_rand(1000,9999) . '.' . $ext;
    if (move_uploaded_file($_FILES['image_file']['tmp_name'], $target_dir . '/' . $fname)) {
        $saved_image = $fname;
    }
}

// Priority 2: image URL (original or user-supplied override)
if (!$saved_image) {
    $img_src = !empty($_POST['image_url_override']) ? $_POST['image_url_override'] : ($_POST['image_url'] ?? '');
    if (!empty($img_src)) {
        $saved_image = NewsScraper::downloadImage($img_src, $target_dir, 'AutoNews_');
    }
}

// Topics (tags) - comma separated -> JSON
$topics_raw = trim($_POST['PostTopic'] ?? '');
$save_topic = null;
if ($topics_raw !== '') {
    $arr = array_values(array_filter(array_map('trim', explode(',', $topics_raw))));
    if ($arr) $save_topic = json_encode($arr, JSON_UNESCAPED_UNICODE);
}

// Publish date
$publishDT = !empty($_POST['publishDateTime']) ? $_POST['publishDateTime'] : $the_time;
try {
    $pd = new DateTime($publishDT);
} catch (Exception $e) {
    $pd = new DateTime();
}

$admin_id = getSingleValue('admin_user', 'admin_security_key', $_COOKIE['Google_SLKA'], 'admin_id');

// Final auto-clean pass on content (safety net even if user skipped clean buttons)
function autoNewsCleanContent($html) {
    // remove ul/ol/li/nav/form/aside blocks
    $html = preg_replace('#<(ul|ol|nav|form|aside|table)\b[\s\S]*?</\1>#i', '', $html);
    $html = preg_replace('#<li\b[\s\S]*?</li>#i', '', $html);
    // remove style/class/id/onclick attrs
    $html = preg_replace('/\s(style|class|id|onclick|onload|data-[a-z-]+)="[^"]*"/i', '', $html);
    // unwrap span/div/section/article/figure
    $html = preg_replace('#</?(span|section|article|figure|figcaption|header|footer)[^>]*>#i', '', $html);
    $html = preg_replace('#<div[^>]*>#i', '', $html);
    $html = preg_replace('#</div>#i', '', $html);
    // <p><h2>x</h2></p> -> <h2>x</h2>
    $html = preg_replace('#<p[^>]*>\s*(<(h[1-6]|blockquote)\b[\s\S]*?</\2>)\s*</p>#i', '$1', $html);
    // wrap stray text after a closing block tag
    $html = preg_replace_callback('#(</(?:p|h[1-6]|blockquote)>)([^<]+)(?=<|$)#i', function($m){
        $t = trim(preg_replace('/\s+/u',' ',$m[2]));
        return $t === '' ? $m[1] : $m[1] . '<p>' . $t . '</p>';
    }, $html);
    // drop paragraphs that are pure URL/domain or known junk
    $junk = '/(Login|EngLogin|আরও পড়ুন|গুগল নিউজ|ফলো করুন|শেয়ার|বিজ্ঞাপন|ই-পেপার|খুঁজুন|Subscribe|সাবস্ক্রাইব|কপি করুন|Copy link)/iu';
    $urlOnly = '#^(https?://\S+|www\.\S+|[a-z0-9-]+\.(?:com|net|org|io|co|news|info|bd|in|uk|gov)(?:/\S*)?)$#i';
    $html = preg_replace_callback('#<(p|h[1-6])[^>]*>([\s\S]*?)</\1>#i', function($m) use ($junk,$urlOnly){
        $text = trim(preg_replace('/\s+/u',' ', strip_tags($m[2])));
        if ($text === '') return '';
        if (preg_match($urlOnly, $text)) return '';
        if (preg_match($junk, $text)) return '';
        if (strtolower($m[1]) === 'p' && mb_strlen($text) < 15) return '';
        return $m[0];
    }, $html);
    // remove empty tags
    $html = preg_replace('#<(p|h[1-6])>\s*(&nbsp;|\xc2\xa0)?\s*</\1>#i', '', $html);
    // strip stray domain text between tags
    $html = preg_replace('#>\s*(https?://\S+|www\.\S+|[a-z0-9-]+\.(?:com|net|org|io|co|news|info|bd)(?:/\S*)?)\s*<#i', '><', $html);
    return trim($html);
}

$content = autoNewsCleanContent($_POST['PostContent'] ?? '');
$credit_line = '';
if ($source_url) {
    $credit_line = '<p><em>সূত্র: <a href="' . htmlspecialchars($source_url, ENT_QUOTES) . '" target="_blank" rel="noopener">'
        . htmlspecialchars($_POST['source_name'] ?? parse_url($source_url, PHP_URL_HOST), ENT_QUOTES)
        . '</a></em></p>';
}
$final_content = $content . $credit_line;


$post_form_data = [
    "PostTitle"             => $_POST['PostTitle'],
    "PostSubtitle"          => $_POST['PostSubtitle'] ?? '',
    "PostContent"           => $final_content,
    "PostImage"             => $saved_image,
    "PostImageOG"           => null,
    "PostImageCaption"      => htmlentities($_POST['PostImageCaption'] ?? '', ENT_QUOTES, 'utf-8'),
    "PostVideoLink"         => $_POST['PostVideoLink'] ?? '',
    "PostDivision"          => $_POST['PostDivision'] ?? '',
    "PostDistrict"          => $_POST['PostDistrict'] ?? '',
    "PostUpazila"           => $_POST['PostUpazila'] ?? '',
    "PostWriterName"        => htmlentities($_POST['PostWriterName'] ?? '', ENT_QUOTES, 'utf-8'),
    "PostWriterDesignation" => htmlentities($_POST['PostWriterDesignation'] ?? '', ENT_QUOTES, 'utf-8'),
    "PostAuthor"            => $_POST['PostAuthor'] ?? null,
    "PostCategory"          => $_POST['PostCategory'] ?? null,
    "PostSubCategory"       => null,
    "PostTopic"             => $save_topic,
    "PostSpotlight"         => $_POST['PostSpotlight'] ?? '',
    "PostLead"              => $_POST['PostLead'] ?? '',
    "PostTicker"            => $_POST['PostTicker'] ?? '',
    "PostAttachment"        => $source_url, // store source URL here for duplicate-check
    "PostStatus"            => $_POST['PostStatus'] ?? 'published',
    "PostDatePublic"        => $pd->format('Y-m-d H:i:s'),
    "PostDayPublic"         => $pd->format('Y-m-d'),
    "PageContentType"       => 'article',
    "PostURL"               => createUlink($_POST['PostTitle']),
    "PostDate"              => $the_time,
    "PostAdmin"             => $admin_id,
];

$insert_now = InsertData('mahamudfutureit_article', $post_form_data);

if ($insert_now) {
    header("Location:article-edit.php?article_id=" . $insert_now);
    exit;
} else {
    header("Location:auto-news.php?status=fail");
    exit;
}
