<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostController extends Controller
{
    /**
     * Display a listing of the posts.
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $query = Post::with(['user', 'media']);

        // Search functionality
        if ($request->has('search') && !empty($request->search)) {
            $search = $request->input('search');
            $query->where('post_text', 'like', "%{$search}%");
        }

        // Filter by post type
        if ($request->has('post_type') && !empty($request->input('post_type'))) {
            $query->where('post_type', $request->input('post_type'));
        }

        $posts = $query->latest()->paginate(15);

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

    /**
     * Display the specified post.
     *
     * @param int $id
     * @return \Illuminate\Contracts\View\View
     */
    public function show($id)
    {
        $post = Post::with([
            'user',
            'media',
            'poll.options',
            'taggedUsers',
            'page',
            'group',
            'fund',
            'parentPost.user',
            'parentPost.media'
        ])->findOrFail($id);

        // Get reaction counts from database
        $reactionCounts = DB::table('posts_reactions')
            ->select('reaction', DB::raw('count(*) as count'))
            ->where('post_id', $id)
            ->groupBy('reaction')
            ->pluck('count', 'reaction')
            ->toArray();

        // Get comment count - use stored count if available, otherwise calculate
        $commentCount = $post->comments_count ?? DB::table('post_comments')
            ->where('post_id', $id)
            ->count();

        // Get share count - use stored count if available, otherwise calculate
        $shareCount = $post->shares_count ?? DB::table('posts')
            ->where('parent_post_id', $id)
            ->count();

        // Get total reactions count
        $totalReactions = array_sum($reactionCounts);

        return view('admin.pages.posts.show', compact('post', 'reactionCounts', 'commentCount', 'shareCount', 'totalReactions'));
    }

    /**
     * Remove the specified post from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        try {
            $post = Post::findOrFail($id);
            
            // Use the deletePosts method from Post model
            // This method handles deletion of all associated data
            $postModel = new Post();
            $postModel->deletePosts([$post->id]);
            
            return redirect()->route('admin.posts.index')
                ->with('success', 'Post deleted successfully.');
        } catch (\Exception $e) {
            return redirect()->route('admin.posts.index')
                ->with('error', 'Error deleting post: ' . $e->getMessage());
        }
    }
}

