<?php

namespace App\Http\Controllers;

use App\Models\Alphabet;
use App\Models\centry;
use App\Models\DonerAndPartner;
use App\Models\gallery;
use App\Models\poet;
use App\Models\Poetries;
use App\Models\Post;
use App\Models\PostComment;
use App\Models\publicPoetCategory;
use App\Models\publicPoetries;
use App\Models\systemAdministration\category;
use App\Models\systemAdministration\info;
use App\Models\systemAdministration\SendUs;
use App\Models\Video;
use App\Models\visitor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Validator;

class publicController extends Controller
{
    public function index()
    {
        // کیچ شوی ویزیټر شمېره (لږ دی، نو یو کیچ کافی دی)
        $visitorCount = Cache::remember('visitor_count', 60, function () {
            $record = visitor::find(1);

            return $record ? $record->qty : 1;
        });

        // د هرې برخې لپاره جلا جلا کیچ
        $info = Cache::remember('home_page_info', 10, function () {
            return Info::latest()->first();
        });

        $categories = Cache::remember('home_page_categories', 10, function () {
            return Category::limit(50)->get(); // د لټون فورمې لپاره
        });

        $poets = Cache::remember('home_page_poets', 10, function () {
            return Poet::limit(100)->get(); // د لټون فورمې لپاره
        });

        $topPoets = Cache::remember('home_page_top_poets', 10, function () {
            return Poet::latest()->limit(8)->get();
        });

        $centries = Cache::remember('home_page_centries', 10, function () {
            $centries = Centry::orderBy('id', 'desc')->get();
            foreach ($centries as $centry) {
                $centry->poets = Poet::where('centry_id', $centry->id)
                    ->limit(6)
                    ->get();
            }

            return $centries;
        });

        $walasi_adab = Cache::remember('home_page_walasi_adab', 10, function () {
            return PublicPoetCategory::all();
        });

        $page = 'index';
        $categories = category::all();

        return view('front-end.index', compact(
            'visitorCount', 'info', 'categories', 'poets', 'topPoets', 'centries', 'walasi_adab', 'page', 'categories'
        ));
    }

    public function categories_index(Request $request)
    {
        $keyword = $request->get('keyword');

        // Regular poetry categories (with Pashto title)
        $categories = category::when($keyword, function ($query, $keyword) {
            return $query->where('title_ps', 'like', "%$keyword%")
                ->orWhere('title_en', 'like', "%$keyword%");
        })->paginate(20, ['*'], 'categories_page');

        // Folk literature categories (with Pashto name)
        $publicCategories = publicPoetCategory::when($keyword, function ($query, $keyword) {
            return $query->where('name_ps', 'like', "%$keyword%")
                ->orWhere('name_en', 'like', "%$keyword%");
        })->paginate(20, ['*'], 'public_page');

        $info = Info::latest()->first();
        $page = 'categories';

        return view('front-end.categories', compact('categories', 'publicCategories', 'info', 'page', 'keyword'));
    }

    public function category_poetries($id)
    {
        $category = category::findOrFail($id);
        $poetries = Poetries::where('cat_id', $id)->paginate(20);
        $info = Info::latest()->first();
        $page = 'category_poetries';

        return view('front-end.category-poetries', compact('category', 'poetries', 'info', 'page'));
    }

    public function poetry_details_single($id)
    {
        $info = Info::latest()->first();
        // د شعر تفصیلات د poet او category سره یوځای راوړئ
        $poetry = Poetries::with(['poet', 'category'])->findOrFail($id);
        $poets = Poet::all(); // د نورو شاعرانو لپاره
        $categories = Category::all(); // د ټولو کټګوریو لپاره
        $page = 'details_single';

        return view('front-end.poerty-details-single', compact('poetry', 'info', 'poets', 'categories', 'page'));
    }

    public function poetry_search(Request $request)
    {
        $perPage = 10;
        $query = Poetries::orderBy('id', 'desc');
        if ($request->category_id != 'any') {
            $query->where('cat_id', $request->category_id);
        }
        if ($request->poet_id != 'any') {
            $query->where('poet_id', $request->poet_id);
            $poet = Poet::find($request->poet_id);
        } else {
            $poet = 'any';
        }
        $poetries = $query->paginate($perPage);
        $info = Info::latest()->first();
        $page = '';

        return view('front-end.poetry_search', compact('info', 'page', 'poet', 'poetries'));
    }
     public function poetry_search1(Request $request)
    {
        $perPage = 12; // or make configurable

        $query = Poetries::with(['poet', 'category'])->orderBy('id', 'desc');

        // Filter by category
        if ($request->filled('category_id') && $request->category_id != 'any') {
            $query->where('cat_id', $request->category_id);
        }

        // Filter by poet
        if ($request->filled('poet_id') && $request->poet_id != 'any') {
            $query->where('poet_id', $request->poet_id);
        }

        // Filter by keyword (search in title, description, or content)
        if ($request->filled('keyword')) {
            $keyword = $request->keyword;
            $query->where(function ($q) use ($keyword) {
                $q->where('title', 'like', "%$keyword%")
                    ->orWhere('description', 'like', "%$keyword%")
                    ->orWhere('content', 'like', "%$keyword%");
            });
        }

        $poetries = $query->paginate($perPage)->appends($request->except('page'));

        // For filter dropdowns
        $categories = Category::orderBy('title_ps')->get();
        $poets = Poet::orderBy('name')->get();

        $info = Info::latest()->first();
        $page = 'search';

        return view('front-end.poetry_search1', compact('poetries', 'categories', 'poets', 'info', 'page'));
    }

    public function poetry_search_details(Request $request)
    {
        $poet = poet::find($request->poet_id);
        $alphabits = Alphabet::all();
        if ($request->category_id == 'any') {
            if ($request->search_text != '') {
                $poetries = Poetries::where('poet_id', $request->poet_id)->where('title', 'like', '%'.$request->search_text.'%')->get();
            } else {
                $poetries = Poetries::where('poet_id', $request->poet_id)->get();

            }
        } else {
            if ($request->search_text != '') {
                $poetries = Poetries::where('poet_id', $request->poet_id)->where('title', 'like', '%'.$request->search_text.'%')->where('cat_id', $request->category_id)->get();
            } else {
                $poetries = Poetries::where('poet_id', $request->poet_id)->where('cat_id', $request->category_id)->get();
            }
        }
        if ($request->search_text != '' && $request->category_id == '') {
            $poetries = Poetries::where('poet_id', $request->poet_id)->where('title', 'like', '%'.$request->search_text.'%')->get();
        }
        $info = Info::latest()->first();
        $page = '';

        return view('front-end.poetry-details-search', compact('info', 'page', 'poet', 'poetries', 'alphabits'));
    }

    public function poet_details($id)
    {
        $poets = poet::limit(6)->get();
        $centries = centry::orderBy('id', 'asc')->get();
        $info = Info::latest()->first();
        $poet = poet::find($id);
        $walasi_adab = publicPoetCategory::all();
        $categories = category::all();
        $page = 'poet_details';

        return view('front-end.poet-details', compact('poets', 'centries', 'info', 'poet', 'walasi_adab', 'page', 'categories'));
    }

    public function poet_poetry_details($id)
    {
        $id_array = explode('-', $id);
        $cat_id = $id_array[0];
        $poet_id = $id_array[1];

        // د شعرونو Pagination
        $poetries = Poetries::where('cat_id', $cat_id)
            ->where('poet_id', $poet_id)
            ->paginate(20); // یا 10، 15

        $info = Info::latest()->first();
        $poet = poet::find($poet_id);
        $poets = poet::all();
        $categories = category::all();
        $cats = category::find($cat_id);
        $alphabits = Alphabet::all();
        $page = '';

        return view('front-end.poet-poetry-details', compact('poetries', 'info', 'poet', 'poets', 'categories', 'page', 'cats', 'alphabits'));
    }

    public function poet_poetry_details_single($id)
    {
        $info = Info::latest()->first();
        // د شعر تفصیلات د poet او category سره یوځای راوړئ
        $poetry = Poetries::with(['poet', 'category'])->findOrFail($id);

        $poets = Poet::all(); // د نورو شاعرانو لپاره
        $categories = Category::all(); // د ټولو کټګوریو لپاره
        $page = 'details_single';

        return view('front-end.poet-poerty-details-single', compact('poetry', 'info', 'poets', 'categories', 'page'));
    }

    public function alphabit_related($alphabit)
    {
        $id_array = explode('-', $alphabit);
        $alphabit = $id_array[0];
        $poet_id = $id_array[1];
        $alphabits = Alphabet::all();
        $info = Info::latest()->first();
        $page = '';
        $poetries = Poetries::where('alphabit', $alphabit)->get();
        $poetries_all = Poetries::all();
        $poets = poet::all();
        $poet = poet::find($poet_id);

        return view('front-end.poet-poetry-alphabit-related', compact('alphabits', 'info', 'page', 'poetries', 'poets', 'poetries_all', 'poet'));
    }

    public function centry_details($id)
    {
        $info = Info::latest()->first();
        $centry = centry::find($id);
        $poets = poet::where('centry_id', $id)->get();
        $centries = centry::orderBy('id', 'desc')->get();
        $page = '';

        return view('front-end.centry-details', compact('info', 'poets', 'centries', 'centry', 'page'));
    }

    public function category_general($id)
    {
        $info = Info::latest()->first();
        $centry = centry::find($id);
        $poetries = Poetries::where('cat_id', $id)->get();
        $poets = poet::where('centry_id', $id)->get();
        $centries = centry::all();
        $page = '';

        return view('front-end.centry-details', compact('info', 'page', 'poetries', 'centry', 'poets', 'centries'));
    }





    public function public_poetry_category($id)
    {
        $category = publicPoetCategory::find($id);
        $poetries = publicPoetries::where('cat_id', $id)->get();
        $info = Info::latest()->first();
        $poets = poet::all();
        $page = '';

        return view('front-end.plcatrelated', compact('category', 'poetries', 'info', 'poets', 'page'));

    }

    public function public_poetry_details($id)
    {
        $poetries = publicPoetries::find($id);
        $category = publicPoetCategory::find($poetries->cat_id);
        $info = Info::latest()->first();
        $poets = poet::all();
        $page = '';

        return view('front-end.plpoetry-single-details', compact('category', 'poetries', 'info', 'poets', 'page'));
    }

    public function video()
    {
        $page = 'video';
        $info = Info::latest()->first();
        $videos = Video::orderBy('id', 'desc')->paginate(10);
        $categories = category::all();
        $recentBlog = Post::orderBy('id', 'desc')->limit(5)->get();

        return view('front-end.videos', compact('info', 'videos', 'page', 'categories', 'recentBlog'));
    }

    public function gallery()
    {
        $page = 'gallery';
        $info = Info::latest()->first();
        $blogs = Post::orderBy('id', 'desc')->limit(10)->get();
        $gallary = gallery::all();

        return view('front-end.gallery', compact('info', 'page', 'blogs', 'gallary'));
    }

    public function blogs()
    {
        $page = 'blog';
        $info = Info::latest()->first();
        $blogs = Post::orderBy('id', 'desc')->paginate(10);
        $categories = category::all();
        $recentBlog = Post::orderBy('id', 'desc')->where('status', 1)->limit(5)->get();

        return view('front-end.blogs', compact('info', 'page', 'blogs', 'categories', 'recentBlog'));
    }

    public function blog_details($id)
    {
        $page = 'service';
        $info = Info::latest()->first();
        $blog = Post::find($id);
        $comments = PostComment::where('post_id', $id)->get();
        $recentBlog = Post::orderBy('id', 'desc')->limit(5)->get();
        $blogs = Post::orderBy('id', 'asc')->where('status', 1)->get();
        $categories = category::all();

        return view('front-end.blog-details', compact('info', 'blog', 'blogs', 'page', 'comments', 'categories', 'recentBlog'));
    }

    public function blog_search(Request $request)
    {
        $page = 'search';
        $info = Info::latest()->first();
        $blogs = Post::where('base_type_id', 1)->where('title', 'like', '%'.$request->keyword.'%')
            ->orWhere('meta_desc', 'like', '%'.$request->keyword.'%')
            ->orWhere('meta_keywords', 'like', '%'.$request->keyword.'%')
            ->get();
        $categories = category::all();
        $recentBlog = Post::orderBy('id', 'desc')->limit(5)->get();

        return view('front-end.blog-filter', compact('info', 'page', 'blogs', 'categories', 'recentBlog'));
    }

    public function contact()
    {
        $page = 'contact';
        $info = Info::latest()->first();

        return view('front-end.contact-us', compact('info', 'page'));
    }

    public function about()
    {
        $page = 'about';
        $info = Info::latest()->first();

        return view('front-end.about-us', compact('info', 'page'));
    }

    public function mission()
    {
        $page = 'mission';
        $info = Info::latest()->first();

        return view('front-end.mission', compact('info', 'page'));
    }

    public function vision()
    {
        $page = 'vision';
        $info = Info::latest()->first();

        return view('front-end.vision', compact('info', 'page'));
    }

    public function faq()
    {
        $page = 'vision';
        $info = Info::latest()->first();

        return view('front-end.faq', compact('info', 'page'));
    }

    public function contact_store(Request $request)
    {
        $data = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'message' => 'required',
        ])->validate();

        $msg = new SendUs;
        $msg->name = $request->name;
        $msg->email = $request->email;
        $msg->subject = $request->subject;
        $msg->message = $request->message;
        $msg->created_at = date('Y-m-d h:i:s');
        $msg->updated_at = date('Y-m-d h:i:s');

        $is_saved = $msg->save();
        if ($is_saved) {
            session()->flash('msg', 'Thanks From Your Contact and Subscription!');

            return back();
        }
    }

    public function feedback()
    {
        $page = 'contact';

        $info = Info::latest()->first();

        return view('front-end.feedback', compact('info', 'page'));
    }

    public function comment_store(Request $request)
    {
        $data = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'message' => 'required',
        ])->validate();

        $msg = new PostComment;
        $msg->post_id = $request->post_id;
        $msg->type_id = $request->type_id;
        $msg->name = $request->name;
        $msg->email = $request->email;
        $msg->subject = $request->subject;
        $msg->message = $request->message;
        $is_saved = $msg->save();
        if ($is_saved) {
            session()->flash('msg', 'Success!');

            return back();
        }

    }

    public function donners()
    {
        $donners = DonerAndPartner::all();
        $page = 'contact';
        $info = Info::latest()->first();

        return view('front-end.donners', compact('donners', 'page', 'info'));
    }

    public function team()
    {
        $donners = DonerAndPartner::where('type_id', 2)->get();
        $page = 'contact';
        $info = Info::latest()->first();

        return view('front-end.team', compact('donners', 'page', 'info'));
    }

    public function donate()
    {
        $donners = DonerAndPartner::where('type_id', 2)->get();
        $page = 'contact';
        $info = Info::latest()->first();

        return view('front-end.donate', compact('donners', 'page', 'info'));
    }

    public function privacy()
    {
        $donners = DonerAndPartner::where('type_id', 2)->get();
        $page = 'contact';
        $info = Info::latest()->first();

        return view('front-end.privacy', compact('donners', 'page', 'info'));
    }

    public function poets()
    {
        $poets = poet::all();
        $page = 'contact';
        $info = Info::latest()->first();

        return view('front-end.poets', compact('poets', 'page', 'info'));
    }
}
