<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Models\Post;
use App\Models\PostComment;
use App\Models\systemAdministration\category;
use App\Models\systemAdministration\language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;

class PostController extends Controller
{
    /**
     * Display a listing of the posts with filtering.
     */
    public function index(Request $request)
    {
        $query = Post::with(['category', 'language']);

        // Apply filters
        if ($request->filled('title')) {
            $query->where('title', 'like', '%' . $request->title . '%');
        }
        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }
        if ($request->filled('language_id')) {
            $query->where('language_id', $request->language_id);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('date_from')) {
            $query->whereDate('date', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('date', '<=', $request->date_to);
        }

        $posts = $query->orderBy('id', 'desc')->paginate(12)->withQueryString();

        $categories = Category::all();
        $languages = Language::all();

        return view('back-end.posts.index', compact('posts', 'categories', 'languages'));
    }

    /**
     * Show the form for creating a new post.
     */
    public function create()
    {
        $languages = Language::all();
        $categories = Category::all();
        return view('back-end.posts.create', compact('languages', 'categories'));
    }

    /**
     * Store a newly created post.
     */
    public function store(Request $request)
    {
        $request->validate([
            'title'       => 'required|max:255',
            'details'     => 'required',
            'meta_desc'   => 'required',
            'meta_keyword'=> 'required',
            'cat_id'      => 'required|exists:categories,id',
            'language_id' => 'required|exists:languages,id',
            'date'        => 'required|date',
            'image'       => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $post = new Post();
        $post->user_id       = Auth::id();
        $post->title         = $request->title;
        $post->language_id   = $request->language_id;
        $post->category_id   = $request->cat_id;
        $post->body          = $request->details;
        $post->meta_desc     = $request->meta_desc;
        $post->meta_keywords = $request->meta_keyword;
        $post->status        = 0;
        $post->date          = $request->date;

        // Handle image upload
        if ($request->hasFile('image')) {
            $date = date('Y-M');
            $filename = 'post_images-' . time() . '-' . $request->file('image')->getClientOriginalName();
            $path = $request->file('image')->storeAs('post_images/' . $date, $filename, 'public');
            $post->image = $path;
        } else {
            $post->image = 'image/noimage.jpg';
        }

        $post->save();

        session()->flash('msg', 'Post created successfully!');
        return redirect()->route('posts.index');
    }

    /**
     * Display the specified post with its comments.
     */
    public function show(Post $post)
    {
        $comments = PostComment::where('post_id', $post->id)->get();
        return view('back-end.posts.show', compact('post', 'comments'));
    }

    /**
     * Show the form for editing the specified post.
     */
    public function edit(Post $post)
    {
        $categories = Category::all();
        $languages = Language::all();
        return view('back-end.posts.edit', compact('post', 'categories', 'languages'));
    }

    /**
     * Update the specified post.
     */
    public function update(Request $request, Post $post)
    {
        $request->validate([
            'title'       => 'required|max:255',
            'details'     => 'required',
            'meta_desc'   => 'required',
            'meta_keyword'=> 'required',
            'cat_id'      => 'required|exists:categories,id',
            'language_id' => 'required|exists:languages,id',
            'date'        => 'required|date',
            'image'       => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $post->title         = $request->title;
        $post->language_id   = $request->language_id;
        $post->category_id   = $request->cat_id;
        $post->body          = $request->details;
        $post->meta_desc     = $request->meta_desc;
        $post->meta_keywords = $request->meta_keyword;
        $post->date          = $request->date;

        if ($request->hasFile('image')) {
            $date = date('Y-M');
            $filename = 'post_images-' . time() . '-' . $request->file('image')->getClientOriginalName();
            $path = $request->file('image')->storeAs('post_images/' . $date, $filename, 'public');
            $post->image = $path;
        }

        $post->save();

        session()->flash('msg', 'Post updated successfully!');
        return redirect()->route('posts.index');
    }

    /**
     * Remove the specified post (soft delete or hard delete).
     */
    public function delete(Post $post)
    {
        $post->delete();
        session()->flash('msg', 'Post deleted!');
        return redirect()->route('posts.index');
    }

    /**
     * Toggle post status (publish/unpublish).
     */
    public function status(Post $post)
    {
        $post->status = !$post->status;
        $post->save();

        $message = $post->status ? 'Post published.' : 'Post unpublished.';
        session()->flash('msg', $message);
        return back();
    }

    /**
     * Delete a comment.
     */
    public function commentDestroy(PostComment $comment)
    {
        $comment->delete();
        return back()->with('msg', 'Comment deleted.');
    }

    /**
     * Mark comment as seen.
     */
    public function commentSeen(PostComment $comment)
    {
        $comment->update(['seen_status' => 1]);
        return back()->with('msg', 'Comment marked as seen.');
    }

    /**
     * Display simple report about posts.
     */
    public function report()
    {
        $totalPosts = Post::count();
        $published = Post::where('status', 1)->count();
        $drafts = Post::where('status', 0)->count();

        $byCategory = Post::select('category_id', DB::raw('count(*) as total'))
                            ->with('category')
                            ->groupBy('category_id')
                            ->get();

        $byLanguage = Post::select('language_id', DB::raw('count(*) as total'))
                            ->with('language')
                            ->groupBy('language_id')
                            ->get();

        return view('back-end.posts.report', compact('totalPosts', 'published', 'drafts', 'byCategory', 'byLanguage'));
    }
}
