<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Category;
use App\Models\PostImage;
use App\Services\WhatsAppService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $query = Post::with(['user', 'category']);

        // Filtros
        if ($request->filled('search')) {
            $query->where('title', 'like', '%' . $request->search . '%');
        }

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $posts = $query->orderBy('created_at', 'desc')->paginate(20);
        $categories = Category::where('active', true)->orderBy('name')->get();

        return view('admin.posts.index', compact('posts', 'categories'));
    }

    public function create()
    {
        $categories = Category::where('active', true)->orderBy('name')->get();
        return view('admin.posts.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'body' => 'required|string',
            'cover_image' => 'nullable|image|max:2048',
        ]);

        $post = new Post($validated);
        $post->user_id = auth()->id();
        $post->slug = Str::slug($request->title);
        
        // Flags
        $post->featured = $request->has('featured');
        $post->is_slide = $request->has('is_slide');
        $post->is_manchete = $request->has('is_manchete');
        $post->is_urgent = $request->has('is_urgent');
        $post->show_in_more_news = $request->has('show_in_more_news');
        
        // Campos opcionais
        $post->subtitle = $request->subtitle;
        $post->excerpt = $request->excerpt;
        $post->hat = $request->hat;
        $post->source = $request->source;
        $post->access = $request->access ?? 'public';
        $post->meta_title = $request->meta_title;
        $post->meta_description = $request->meta_description;
        $post->canonical = $request->canonical;
        
        // Tags
        if ($request->tags) {
            $post->tags = is_array($request->tags) ? $request->tags : explode(',', $request->tags);
        }
        
        // Upload cover image
        if ($request->hasFile('cover_image')) {
            $post->cover_image = $request->file('cover_image')->store('posts', 'public');
        }
        
        // Status e publicação
        $post->status = $request->status ?? 'draft';
        if ($request->status === 'published' && !$post->published_at) {
            $post->published_at = now();
        } elseif ($request->published_at) {
            $post->published_at = $request->published_at;
        }
        
        $post->save();

        // Enviar notificações se solicitado
        if ($request->whatsapp_notification && $post->status === 'published') {
            $this->sendWhatsAppNotifications($post);
        }

        return redirect()->route('admin.posts.index')
            ->with('success', 'Notícia criada com sucesso!');
    }

    public function edit(Post $post)
    {
        $categories = Category::where('active', true)->orderBy('name')->get();
        return view('admin.posts.edit', compact('post', 'categories'));
    }

    public function update(Request $request, Post $post)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'body' => 'required|string',
            'cover_image' => 'nullable|image|max:2048',
        ]);

        $post->fill($validated);
        $post->slug = Str::slug($request->title);
        
        // Flags
        $post->featured = $request->has('featured');
        $post->is_slide = $request->has('is_slide');
        $post->is_manchete = $request->has('is_manchete');
        $post->is_urgent = $request->has('is_urgent');
        $post->show_in_more_news = $request->has('show_in_more_news');
        
        // Upload cover image
        if ($request->hasFile('cover_image')) {
            if ($post->cover_image) {
                Storage::disk('public')->delete($post->cover_image);
            }
            $post->cover_image = $request->file('cover_image')->store('posts', 'public');
        }
        
        $post->save();

        return redirect()->route('admin.posts.index')
            ->with('success', 'Notícia atualizada com sucesso!');
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return redirect()->route('admin.posts.index')
            ->with('success', 'Notícia excluída com sucesso!');
    }

    private function sendWhatsAppNotifications(Post $post)
    {
        $whatsapp = app(WhatsAppService::class);
        $readers = \App\Models\Reader::where('status', 'active')
            ->where('receive_private', true)
            ->get();

        foreach ($readers as $reader) {
            // Verificar se tem interesse na categoria
            $interests = $reader->categories_interest ?? [];
            if (!empty($interests) && !in_array($post->category_id, $interests)) {
                continue;
            }

            $message = "📰 *Nova matéria publicada!*\n\n";
            $message .= "📌 *{$post->title}*\n";
            $message .= "🕒 " . $post->published_at->format('d/m/Y H:i') . "\n\n";
            $message .= ($post->excerpt ?? substr(strip_tags($post->body), 0, 150)) . "...\n\n";
            $message .= "🔗 Leia agora: {$post->url}";

            $whatsapp->sendText($reader->whatsapp_number, $message);
        }
    }
}

