<meta charset="utf8">

<?php

ob_start();

error_reporting(0);
set_time_limit(0);


function getPageContent($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

function downloadAndConvertImage($image_url, $save_path) {
    $image_content = file_get_contents($image_url);
    $temp_image_path = tempnam(sys_get_temp_dir(), 'temp_image');
    file_put_contents($temp_image_path, $image_content);
    
    $image_info = getimagesize($temp_image_path);
    $image_type = $image_info[2];
    
    if ($image_type == IMAGETYPE_JPEG || $file_extension == 'jpg') {
    $image = imagecreatefromjpeg($temp_image_path);
    } elseif ($image_type == IMAGETYPE_PNG) {
        $image = imagecreatefrompng($temp_image_path);
    } elseif ($image_type == IMAGETYPE_WEBP) {
        $image = imagecreatefromwebp($temp_image_path);
    } else {
        echo "Desteklenmeyen resim formatı.<br>";
        return false;
    }
    
    if (!file_exists(dirname($save_path))) {
        mkdir(dirname($save_path), 0777, true);
    }
    
    imagewebp($image, $save_path, 80);
    imagedestroy($image);
    unlink($temp_image_path);
    
    return true;
}

function getSeoSlugFromUrl($url) {
    $path = parse_url($url, PHP_URL_PATH);
    $slug = basename($path, '.html');
    return $slug;
}

function fixContentEncoding($content) {
    $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
    $content = mb_convert_encoding($content, 'UTF-8', 'auto');
    
    return $content;
}

function saveArticleImages($content, $year, $month, $day, $safe_title) {
    preg_match_all('/<img.*?src="(.*?)".*?>/i', $content, $image_matches);
    
    if (!empty($image_matches[1])) {
        foreach ($image_matches[1] as $image_url) {
            $image_name = basename(parse_url($image_url, PHP_URL_PATH), '.jpg') . '-' . time() . '.webp';
            $image_save_path = "uploads/images/news/$year/$month/$day/$image_name";
            downloadAndConvertImage($image_url, $image_save_path);
            $content = str_replace($image_url, $image_save_path, $content);
        }
    }
    
    return $content;
}

// Veritabanına bağlan
$servername = "localhost";
$username = "kocaeliduysun_habercode";
$password = "Enesbaba33*";
$dbname = "kocaeliduysun_habercode";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Bağlantı başarısız: " . $conn->connect_error);
}

mysqli_set_charset($conn,"utf8mb4");


function checkCategory($category_name, $conn) {
    // Kategori sorgusunu LIKE ile yapalım
    $sql = "SELECT id FROM categories WHERE name LIKE ?";
    $stmt = $conn->prepare($sql);

    // Joker karakterleri (%) ekleyerek kategoriyi arayalım
    $category_name = '%' . $category_name . '%';

    $stmt->bind_param("s", $category_name);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($category_id);
        $stmt->fetch();
        return $category_id;
    }

    return 28; // Varsayılan kategori ID
}
function insertNews($slug, $title, $short_desc, $description, $image_filename, $publish_date, $publish_time, $category_id, $change_date_time, $conn) {
    // Aynı slug ile haber var mı kontrol et
    $sql = "SELECT id FROM news WHERE slug = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $slug);
    $stmt->execute();
    $stmt->store_result();

    // Aynı slug varsa eklemiyoruz
    if ($stmt->num_rows > 0) {
       // echo "Bu haber zaten mevcut: $slug<br>";
        return;
    }

    // SQL sorgusuna `change_date_time` sütununu ekleyelim
    $insert_sql = "
    INSERT INTO news 
    (category_id, date, time, name, headline_title, mainheadline_title, short_description, description, author_id, views_count, status, news_image, headline_image, category_image, is_headline, is_lastminute, is_breaking, is_photogallary, is_videogallary, created_at, slug, mainheadline_order, headline_order, change_date_time) 
    VALUES 
    (?, ?, ?, ?, ?, ?, ?, ?, 1, '0', 1, ?, ?, ?, 0, 0, 0, 0, 0, ?, ?, 9999, 9999, ?)";

    // Yayın tarihi ve saati `created_at` ve `change_date_time` için ayarlanıyor
    $created_at = date('Y-m-d H:i:s', strtotime("$publish_date $publish_time"));

    // Parametreleri `bind_param` içine ekliyoruz, `change_date_time` da dahil edildi
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param(
        "isssssssssssss", // Burada 14 parametre var, stringler ve integerler için uygun formatlar
        $category_id, $publish_date, $publish_time,
        $title, $title, $title, $short_desc, $description,
        $image_filename, $image_filename, $image_filename,
        $created_at, $slug, $change_date_time // `change_date_time` eklendi
    );
    $stmt->execute();

    //echo "Haber başarıyla eklendi: $title<br>";
}

                $page=$_GET['page'];

                $curl = curl_init();

                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://kocaeliduysun.net/wp-admin/admin-ajax.php',
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'POST',
                  CURLOPT_POSTFIELDS => array('page' => $page,'count' => '100','action' => 'sunset_load_moreNews','cat' => '586','offset' => '0'),
                  CURLOPT_HTTPHEADER => array(
                    'Cookie: accessed=yes; accessed2=yes'
                  ),
                ));

        $response = curl_exec($curl);

        curl_close($curl);

        $tekhaber=explode('<div data-page="'.($page+1).'">',$response);
        $tekcount=count($tekhaber)-1;

        for($i=1;$i<=$tekcount;$i++){
            $tekhaber=explode('<div data-page="'.($page+1).'">',$response);
            $tekhaber=explode('</div>',$tekhaber[$i]);

            $haberlink=explode('href="',$tekhaber[0]);
            $haberlink=explode('"',$haberlink[1]);

            $haberresim=explode('src="',$tekhaber[0]);
            $haberresim=explode('"',$haberresim[1]);

            $haberisim=explode('alt="',$tekhaber[0]);
            $haberisim=explode('"',$haberisim[1]);

            $haberic=file_get_contents($haberlink[0]);
            $seo_slug = getSeoSlugFromUrl($haberlink[0]);

            $haberresim=explode('<meta property="og:image" content="',$haberic);
            $haberresim=explode('"',$haberresim[1]);


            $kisaaciklama=explode('<meta name="description" content="', $haberic);
            $kisaaciklama=explode('"',$kisaaciklama[1]);

            $date=explode('<meta property="article:published_time" content="',$haberic);
            $date=explode('"',$date[1]);

            $originalDate = $date[0];

            $createdAt = $originalDate;

            $dateTime = new DateTime($originalDate);

            // Tarih (Y-m-d) formatında
            $date = $dateTime->format('d.m.Y');

            // Saat (H:i) formatında, saniyeler hariç
            $time = $dateTime->format('H:i');



            $safe_title = preg_replace('/[^a-zA-Z0-9-_]/', '', str_replace(' ', '-', strtolower($seo_slug)));
            $image_save_path = "uploads/images/news/".$dateTime->format('Y')."/".$dateTime->format('m')."/".$dateTime->format('d')."/$safe_title-" . time() . ".webp";
            
            downloadAndConvertImage($haberresim[0], $image_save_path);

            $haberdetay=explode('$("#newsRead .bottom .left .detail p").css("font-size", currentFont);',$haberic);
            $haberdetay=explode('</div>',$haberdetay[1]);

            $haberdetay[0]=str_replace('});', '', $haberdetay[0]);
            $haberdetay[0]=str_replace('</script>', '', $haberdetay[0]);

            $habericerik_cleaned = saveArticleImages($haberdetay[0], $dateTime->format('Y'),$dateTime->format('m'), $dateTime->format('d'), $safe_title);
            $habericerik_cleaned = fixContentEncoding($habericerik_cleaned, 'UTF-8', 'auto');
            $short_desc = fixContentEncoding($kisaaciklama[0], 'UTF-8', 'auto');
            $title = fixContentEncoding($haberisim[0], 'UTF-8', 'auto');


            insertNews(
            $seo_slug, 
            $title, 
            $short_desc, 
            $habericerik_cleaned, 
            basename($image_save_path), 
            $date, 
            $time, 
            "31", 
            '', 
            $conn
            );
    }

$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$nextPage = $currentPage + 1;

// Veritabanı bağlantısını kapat
$conn->close();

// Eğer sayfa işlemi tamamlanmışsa, bir sonraki sayfaya geçiş yap
if ($currentPage < 80) { // Örneğin 10 sayfa sınırlı bir döngü ile durdurabilirsiniz
    header("Location: ?page=$nextPage");
    exit;
} else {
    echo "Tüm sayfalar işlendi.";
}


ob_end_flush();

?>
