<?php

namespace App\Http\Controllers\API;

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

class NewsReceiverController extends Controller
{
    /**
     * Ana siteden gelen haberi al ve kaydet
     */
    public function receiveNews(Request $request)
    {
        // API Key kontrolü
        $apiKey = $request->header('X-API-Key');
        if (!$this->validateApiKey($apiKey)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        try {
            $newsData = $request->input('news_data');
            $images = $request->input('images', []);

            // Aynı haber zaten var mı kontrol et
            $existingNews = News::where('original_news_id', $newsData['id'])
                ->where('source_site', 'main_site')
                ->first();

            if ($existingNews) {
                return response()->json([
                    'success' => true,
                    'message' => 'Haber zaten mevcut',
                    'news_id' => $existingNews->id
                ]);
            }

            // 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'] . '-' . time(); // Benzersiz slug
            $news->date = $newsData['date'];
            $news->time = $newsData['time'];
            $news->status = $newsData['status'];
            $news->views_count = $newsData['views_count'];

            // 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;

            // 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 kaydet
            if (!empty($images)) {
                $news->news_image = $this->saveImage($images['news_image'] ?? null, 'news');
                $news->headline_image = $this->saveImage($images['headline_image'] ?? null, 'headline');
                $news->mainheadline_image = $this->saveImage($images['mainheadline_image'] ?? null, 'mainheadline');
            }

            $news->save();

            Log::info('Ana siteden haber alındı', [
                'original_id' => $newsData['id'],
                'new_id' => $news->id,
                'title' => $news->name
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Haber başarıyla alındı',
                'news_id' => $news->id
            ]);

        } catch (\Exception $e) {
            Log::error('Haber alma hatası', [
                'error' => $e->getMessage(),
                'news_data' => $request->input('news_data')
            ]);

            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 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;
    }

    /**
     * Base64 resmi kaydet
     */
    private function saveImage($base64Image, $type)
    {
        if (empty($base64Image)) {
            return null;
        }

        try {
            $imageData = base64_decode($base64Image);
            $filename = 'imported_' . $type . '_' . time() . '.jpg';
            $path = 'uploads/images/' . $filename;
            
            Storage::disk('public')->put($path, $imageData);
            
            return $filename;
        } catch (\Exception $e) {
            Log::error('Resim kaydetme hatası', ['error' => $e->getMessage()]);
            return null;
        }
    }

    /**
     * API Key doğrulama
     */
    private function validateApiKey($apiKey)
    {
        $validKeys = [
            'subsite_key_1',
            'subsite_key_2',
            'subsite_key_3',
            // Alt site sayısına göre eklenebilir
        ];

        return in_array($apiKey, $validKeys);
    }

    /**
     * Site sağlık kontrolü
     */
    public function healthCheck()
    {
        return response()->json([
            'status' => 'online',
            'timestamp' => now(),
            'version' => '1.0.0'
        ]);
    }
}