<?php

namespace App\Services;

use App\Models\News;
use App\Models\Category;
use App\Models\Authors;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class NewsSyncService
{
    private $mainSiteUrl;
    private $apiKey;

    public function __construct()
    {
        $this->mainSiteUrl = config('app.main_site_url', 'https://anahaber.com');
        $this->apiKey = config('app.api_key', 'subsite_key_1');
    }

    /**
     * Ana siteden paylaşılan haberleri senkronize et
     */
    public function syncFromMainSite()
    {
        try {
            Log::info('Starting news sync from main site');

            // Yazarları senkronize et
            $this->syncAuthors();

            // Paylaşılan haberleri senkronize et
            $this->syncSharedNews();
            
            // Paylaşımdan kaldırılan haberleri kontrol et
            $this->syncUnsharedNews();
            
            // Daha önce çekilmiş haberlerin durumunu kontrol et
            $this->checkExistingNewsStatus();

            // Son senkronizasyon zamanını güncelle
            $this->updateLastSyncTime();

            Log::info('News sync completed successfully');
            return true;

        } catch (\Exception $e) {
            Log::error('News sync failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Paylaşılan haberleri senkronize et
     */
    private function syncSharedNews()
    {
        // Son senkronizasyon zamanını al
        $lastSync = $this->getLastSyncTime();
        
        $response = Http::withHeaders([
            'X-API-Key' => $this->apiKey,
            'Accept' => 'application/json'
        ])->get($this->mainSiteUrl . '/api/shared-news', [
            'since' => $lastSync
        ]);

        if (!$response->successful()) {
            Log::error('Failed to fetch shared news: ' . $response->body());
            return false;
        }

        $sharedNews = $response->json()['data'] ?? [];

        foreach ($sharedNews as $newsData) {
            $this->importNews($newsData);
        }

        return true;
    }

    /**
     * Paylaşımdan kaldırılan haberleri kontrol et ve pasif yap
     */
    private function syncUnsharedNews()
    {
        try {
            Log::info('Starting unshared news sync from main site');

            // Son senkronizasyon zamanını al
            $lastSync = $this->getLastSyncTime();
            
            $response = Http::withHeaders([
                'X-API-Key' => $this->apiKey,
                'Accept' => 'application/json'
            ])->get($this->mainSiteUrl . '/api/unshared-news', [
                'since' => $lastSync
            ]);

            if (!$response->successful()) {
                Log::error('Failed to fetch unshared news: ' . $response->body());
                return false;
            }

            $unsharedNews = $response->json()['data'] ?? [];
            Log::info('Found ' . count($unsharedNews) . ' unshared news items');

            foreach ($unsharedNews as $newsData) {
                Log::info('Processing unshared news: ' . $newsData['id'] . ' - ' . $newsData['name']);
                $this->deactivateNews($newsData);
            }

            Log::info('Unshared news sync completed successfully');
            return true;

        } catch (\Exception $e) {
            Log::error('Unshared news sync failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Haberi yerel veritabanına import et
     */
    private function importNews($newsData)
    {
        // Aynı haber zaten var mı kontrol et
        $existingNews = News::where('original_news_id', $newsData['id'])
            ->where('source_site', 'main_site')
            ->first();

        if ($existingNews) {
            // Haber güncellenmiş mi kontrol et
            if ($existingNews->updated_at < $newsData['updated_at']) {
                $this->updateNews($existingNews, $newsData);
            }
            return;
        }

        // Yeni haber oluştur
        $news = new News();
        $news->original_news_id = $newsData['id'];
        $news->source_site = 'main_site';
        $news->is_shared = 1;
        $news->shared_at = now();

        // Temel haber bilgileri
        $news->name = $newsData['name'];
        $news->short_description = $newsData['short_description'];
        $news->description = $newsData['description'];
        $news->slug = $newsData['slug'];
        $news->date = $newsData['date'];
        $news->time = $newsData['time'];
        $news->status = $newsData['status'];
        $news->views_count = $newsData['views_count'];
        
        // Başlık alanları
        $news->mainheadline_title = $newsData['mainheadline_title'] ?? null;
        $news->headline_title = $newsData['headline_title'] ?? null;

        // Haber özellikleri
        $news->is_headline = $newsData['is_headline'] ?? 0;
        $news->is_lastminute = $newsData['is_lastminute'] ?? 0;
        $news->is_breaking = $newsData['is_breaking'] ?? 0;
        $news->is_photogallary = $newsData['is_photogallary'] ?? 0;
        $news->is_videogallary = $newsData['is_videogallary'] ?? 0;
        $news->is_mainheadline = $newsData['is_mainheadline'] ?? 0;
        $news->is_topheadline = $newsData['is_topheadline'] ?? 0;
        $news->corner_post = $newsData['corner_post'] ?? 0;

        // Kategori mapping
        if (isset($newsData['category']['name'])) {
            $category = $this->findOrCreateCategory($newsData['category']);
            $news->category_id = $category->id;
        }

        // Yazar mapping
        if (isset($newsData['author']['name'])) {
            $author = $this->findOrCreateAuthor($newsData['author']);
            $news->author_id = $author->id;
        }

        // Resimleri kopyala
        if (isset($newsData['news_image'])) {
            $news->news_image = $this->copyImage($newsData['news_image']);
            Log::info('news_image set to: ' . $news->news_image);
        }

        if (isset($newsData['headline_image'])) {
            $news->headline_image = $this->copyImage($newsData['headline_image']);
            Log::info('headline_image set to: ' . $news->headline_image);
        }

        if (isset($newsData['mainheadline_image'])) {
            $news->mainheadline_image = $this->copyImage($newsData['mainheadline_image']);
            Log::info('mainheadline_image set to: ' . $news->mainheadline_image);
        }

        if (isset($newsData['category_image'])) {
            $news->category_image = $this->copyImage($newsData['category_image']);
            Log::info('category_image set to: ' . $news->category_image);
        }

        // Diğer alanlar
        $news->tag = $newsData['tag'] ?? null;
        $news->kaynak = $newsData['kaynak'] ?? null;
        $news->bar_background_color = $newsData['bar_background_color'] ?? null;
        $news->bar_text_color = $newsData['bar_text_color'] ?? null;
        $news->bar_text = $newsData['bar_text'] ?? null;

        $news->save();

        Log::info('Imported news: ' . $news->name);
    }

    /**
     * Mevcut haberi güncelle
     */
    private function updateNews($news, $newsData)
    {
        $news->name = $newsData['name'];
        $news->short_description = $newsData['short_description'];
        $news->description = $newsData['description'];
        $news->status = $newsData['status'];
        $news->is_headline = $newsData['is_headline'] ?? 0;
        $news->is_lastminute = $newsData['is_lastminute'] ?? 0;
        $news->is_breaking = $newsData['is_breaking'] ?? 0;
        $news->is_photogallary = $newsData['is_photogallary'] ?? 0;
        $news->is_videogallary = $newsData['is_videogallary'] ?? 0;
        $news->is_mainheadline = $newsData['is_mainheadline'] ?? 0;
        $news->is_topheadline = $newsData['is_topheadline'] ?? 0;
        $news->corner_post = $newsData['corner_post'] ?? 0;
        
        // Başlık alanları
        $news->mainheadline_title = $newsData['mainheadline_title'] ?? null;
        $news->headline_title = $newsData['headline_title'] ?? null;
        
        // Diğer alanlar
        $news->tag = $newsData['tag'] ?? null;
        $news->kaynak = $newsData['kaynak'] ?? null;
        $news->bar_background_color = $newsData['bar_background_color'] ?? null;
        $news->bar_text_color = $newsData['bar_text_color'] ?? null;
        $news->bar_text = $newsData['bar_text'] ?? null;
        
        // Resimleri güncelle
        if (isset($newsData['news_image'])) {
            $news->news_image = $this->copyImage($newsData['news_image']);
        }
        if (isset($newsData['headline_image'])) {
            $news->headline_image = $this->copyImage($newsData['headline_image']);
        }
        if (isset($newsData['mainheadline_image'])) {
            $news->mainheadline_image = $this->copyImage($newsData['mainheadline_image']);
        }
        if (isset($newsData['category_image'])) {
            $news->category_image = $this->copyImage($newsData['category_image']);
        }
        
        $news->save();

        Log::info('Updated news: ' . $news->name);
    }

    /**
     * Kategori bul veya oluştur
     */
    private function findOrCreateCategory($categoryData)
    {
        $category = Category::where('name', $categoryData['name'])->first();
        
        if (!$category) {
            $category = new Category();
            $category->name = $categoryData['name'];
            $category->slug = $categoryData['slug'] ?? str_slug($categoryData['name']);
            $category->status = 1;
            $category->save();
        }

        return $category;
    }

    /**
     * Yazar bul veya oluştur
     */
    private function findOrCreateAuthor($authorData)
    {
        $author = Authors::where('name', $authorData['name'])->first();
        
        if (!$author) {
            $author = new Authors();
            $author->name = $authorData['name'];
            $author->slug = $authorData['slug'] ?? str_slug($authorData['name']);
            $author->status = 1;
            $author->save();
        }

        return $author;
    }

    /**
     * Resmi ana siteden kopyala
     */
    private function copyImage($imagePath)
    {
        if (empty($imagePath)) {
            return null;
        }

        // Debug log
        Log::info('copyImage input: ' . $imagePath);

        // Görsel yolu zaten tam URL ise, panel.manevrahaber.com ile değiştir
        if (strpos($imagePath, 'http') === 0) {
            // manevrahaber.com'u panel.manevrahaber.com ile değiştir
            $result = str_replace('manevrahaber.com', 'panel.manevrahaber.com', $imagePath);
            Log::info('copyImage output (replaced URL): ' . $result);
            return $result;
        }

        // Görsel yolu ana site URL'si ile birleştir ve tarih klasörü ekle
        $result = 'https://panel.manevrahaber.com/uploads/images/news/' . date('Y/m/d') . '/' . $imagePath;
        Log::info('copyImage output (constructed): ' . $result);
        return $result;
    }

    /**
     * Son senkronizasyon zamanını al
     */
    private function getLastSyncTime()
    {
        $lastSyncFile = storage_path('app/last_sync.txt');
        
        if (file_exists($lastSyncFile)) {
            return file_get_contents($lastSyncFile);
        }
        
        // İlk senkronizasyon için son 1 saat
        return now()->subHour()->toISOString();
    }

    /**
     * Ana siteden yazarları senkronize et
     */
    private function syncAuthors()
    {
        try {
            Log::info('Starting authors sync from main site');
            
            $response = Http::withHeaders([
                'X-API-Key' => $this->apiKey,
                'Accept' => 'application/json'
            ])->get($this->mainSiteUrl . '/api/all-authors');

            if (!$response->successful()) {
                Log::error('Failed to fetch authors: ' . $response->body());
                return false;
            }

            $authors = $response->json()['data'] ?? [];
            Log::info('Found ' . count($authors) . ' authors to sync');

            // Ana sitedeki tüm yazarları al
            $mainSiteAuthorIds = [];
            foreach ($authors as $authorData) {
                $mainSiteAuthorIds[] = $authorData['id'];
                $this->syncAuthor($authorData);
            }

            // Alt sitede olan ama ana sitede olmayan yazarları sil
            $this->removeDeletedAuthors($mainSiteAuthorIds);

            Log::info('Authors sync completed successfully');
            return true;

        } catch (\Exception $e) {
            Log::error('Authors sync failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Yazarı senkronize et
     */
    private function syncAuthor($authorData)
    {
        $author = Authors::where('name', $authorData['name'])->first();
        
        if (!$author) {
            // Yeni yazar oluştur
            $author = new Authors();
            $author->name = $authorData['name'];
            $author->mail = $authorData['mail'] ?? null;
            $author->image = $authorData['image'] ?? null;
            $author->social_media = $authorData['social_media'] ?? null;
            $author->code = $authorData['code'] ?? null;
            $author->slug = $authorData['slug'] ?? str_slug($authorData['name']);
            $author->type = $authorData['type'] ?? null;
            $author->ads_side = $authorData['ads_side'] ?? null;
            $author->save();
            
            Log::info('Created new author: ' . $author->name);
        } else {
            // Mevcut yazarı güncelle
            $oldName = $author->name;
            
            $author->name = $authorData['name'];
            $author->mail = $authorData['mail'] ?? null;
            $author->image = $authorData['image'] ?? null;
            $author->social_media = $authorData['social_media'] ?? null;
            $author->code = $authorData['code'] ?? null;
            $author->slug = $authorData['slug'] ?? str_slug($authorData['name']);
            $author->type = $authorData['type'] ?? null;
            $author->ads_side = $authorData['ads_side'] ?? null;
            $author->save();
            
            if ($oldName != $author->name) {
                Log::info('Updated author: ' . $oldName . ' -> ' . $author->name);
            }
        }
        
        return $author;
    }

    /**
     * Ana sitede olmayan yazarları sil
     */
    private function removeDeletedAuthors($mainSiteAuthorIds)
    {
        try {
            // Alt sitede olan ama ana sitede olmayan yazarları bul
            $deletedAuthors = Authors::whereNotIn('id', $mainSiteAuthorIds)->get();
            
            foreach ($deletedAuthors as $author) {
                // Bu yazara ait haberlerin yazar_id'sini null yap
                News::where('author_id', $author->id)->update(['author_id' => null]);
                
                // Yazarı sil
                $author->delete();
                Log::info('Deleted author: ' . $author->name);
            }
            
            if ($deletedAuthors->count() > 0) {
                Log::info('Removed ' . $deletedAuthors->count() . ' deleted authors');
            }
            
        } catch (\Exception $e) {
            Log::error('Failed to remove deleted authors: ' . $e->getMessage());
        }
    }

    /**
     * Daha önce çekilmiş haberlerin durumunu kontrol et
     */
    private function checkExistingNewsStatus()
    {
        try {
            Log::info('Checking existing news status from main site');

            // Alt sitede ana siteden çekilmiş tüm haberleri al
            $existingNews = News::where('source_site', 'main_site')
                ->whereNotNull('original_news_id')
                ->get();

            Log::info('Found ' . $existingNews->count() . ' existing news items to check');

            foreach ($existingNews as $localNews) {
                // Ana sitede bu haberin durumunu kontrol et
                $response = Http::withHeaders([
                    'X-API-Key' => $this->apiKey,
                    'Accept' => 'application/json'
                ])->get($this->mainSiteUrl . '/api/shared-news/' . $localNews->original_news_id);

                if ($response->successful()) {
                    $mainSiteNews = $response->json()['news_data'] ?? null;
                    
                    if ($mainSiteNews) {
                        // Haber ana sitede var, durumunu kontrol et
                        if ($mainSiteNews['is_shared'] == 0) {
                            // Paylaşımdan kaldırılmış, pasif yap
                            $localNews->status = 0;
                            $localNews->save();
                            Log::info('Deactivated existing news (unshared): ' . $localNews->name);
                        }
                    } else {
                        // Haber ana sitede bulunamadı (silinmiş), pasif yap
                        $localNews->status = 0;
                        $localNews->save();
                        Log::info('Deactivated existing news (deleted): ' . $localNews->name);
                    }
                } else {
                    // API'den haber alınamadı (muhtemelen silinmiş), pasif yap
                    $localNews->status = 0;
                    $localNews->save();
                    Log::info('Deactivated existing news (API error): ' . $localNews->name);
                }
            }

            Log::info('Existing news status check completed');
            return true;

        } catch (\Exception $e) {
            Log::error('Existing news status check failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Haberi pasif yap
     */
    private function deactivateNews($newsData)
    {
        $news = News::where('original_news_id', $newsData['id'])
            ->where('source_site', 'main_site')
            ->first();

        if ($news) {
            $oldStatus = $news->status;
            $news->status = 0; // Pasif yap
            $news->save();
            
            Log::info('Deactivated news: ' . $news->name . ' (Status changed from ' . $oldStatus . ' to 0)');
        } else {
            Log::warning('News not found for deactivation: ' . $newsData['id'] . ' - ' . $newsData['name']);
        }
    }

    /**
     * Son senkronizasyon zamanını güncelle
     */
    private function updateLastSyncTime()
    {
        $lastSyncFile = storage_path('app/last_sync.txt');
        file_put_contents($lastSyncFile, now()->toISOString());
    }
}
