<?php
/**
 * Auto News - Fetch endpoint (AJAX)
 * URL দিলে JSON response পাঠায়
 */
require_once('config.php');
require_once('inc/NewsScraper.php');

header('Content-Type: application/json; charset=utf-8');

// Auth check
if (empty($_COOKIE['Google_SLKA'])) {
    echo json_encode(['ok' => false, 'msg' => 'Unauthorized']);
    exit;
}

$url = trim($_POST['url'] ?? '');
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    echo json_encode(['ok' => false, 'msg' => 'সঠিক URL দিন']);
    exit;
}

try {
    $scraper = new NewsScraper($url);
    $data = $scraper->scrape();

    if (empty($data['title']) || empty($data['content'])) {
        echo json_encode(['ok' => false, 'msg' => 'নিউজ data পাওয়া যায়নি। অন্য লিংক চেষ্টা করুন।']);
        exit;
    }

    echo json_encode(['ok' => true, 'data' => $data], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    echo json_encode(['ok' => false, 'msg' => 'Error: ' . $e->getMessage()]);
}
