<?php

namespace App\Http\Controllers;

use App\Models\Poet;
use App\Models\Centry;
use App\Models\Poetries;
use App\Models\systemAdministration\category;
use App\Models\systemAdministration\subCategory;
use App\Models\Alphabet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PoetController extends Controller
{
    /**
     * Display a listing of poets with filtering.
     */
    public function index(Request $request)
    {
        $query = Poet::with('centry');

        if ($request->filled('name')) {
            $query->where('name', 'like', '%' . $request->name . '%');
        }
        if ($request->filled('centry_id')) {
            $query->where('centry_id', $request->centry_id);
        }
        if ($request->filled('address')) {
            $query->where('address', 'like', '%' . $request->address . '%');
        }

        $poets = $query->orderBy('id', 'desc')->paginate(20)->withQueryString();
        $centries = Centry::all();

        return view('back-end.poets.index', compact('poets', 'centries'));
    }

    /**
     * Show form for creating new poet.
     */
    public function create()
    {
        $centries = Centry::all();
        return view('back-end.poets.create', compact('centries'));
    }

    /**
     * Store a newly created poet.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'      => 'required|max:255',
            'bio'       => 'required',
            'address'   => 'required',
            'centry_id' => 'required|exists:centries,id',
            'image'     => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $poet = new Poet();
        $poet->user_id      = Auth::id();
        $poet->name         = $request->name;
        $poet->last_name    = $request->last_name;
        $poet->father_name  = $request->father_name;
        $poet->centry_id    = $request->centry_id;
        $poet->address      = $request->address;
        $poet->email        = $request->email;
        $poet->dob          = $request->dob;
        $poet->phone        = $request->phone;
        $poet->bio          = $request->bio;

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

        $poet->save();
        session()->flash('msg', 'Poet created successfully!');
        return redirect()->route('poets.index');
    }

    /**
     * Display the specified poet with his poetries.
     */
    public function show(Poet $poet)
    {
        $categories = Category::all();
        $poetries = Poetries::where('poet_id', $poet->id)
                            ->with('category')
                            ->orderBy('id', 'desc')
                            ->paginate(10);
        $cat_title = "All";
        return view('back-end.poets.show', compact('poet', 'categories', 'poetries', 'cat_title'));
    }

    /**
     * Show poetries filtered by category.
     */
    public function categoryWise($id)
    {
        $ids = explode('-', $id);
        $cat_id = $ids[0];
        $poet_id = $ids[1];

        $poet = Poet::findOrFail($poet_id);
        $categories = Category::all();
        $category = Category::findOrFail($cat_id);
        $poetries = Poetries::where('poet_id', $poet_id)
                            ->where('cat_id', $cat_id)
                            ->with('category')
                            ->paginate(10);
        $cat_title = $category->title_en;

        return view('back-end.poets.show', compact('poet', 'categories', 'poetries', 'cat_title', 'category'));
    }

    /**
     * Show form to create a new poetry (all categories) – matches route 'poetries.all_poetry_create'
     */
    public function all_poetry_create($id)
    {
        $poet = Poet::findOrFail($id);
        $categories = Category::all();
        $alphabits = Alphabet::all();
        return view('back-end.poets.poetries.poetry-create-all', compact('poet', 'categories', 'alphabits'));
    }

    /**
     * Store a new poetry (all categories) – matches route 'poetries.all_poetry_store'
     */
    public function all_poetry_store(Request $request)
    {
        $request->validate([
            'title'   => 'required',
            'body'    => 'required',
            'cat_id'  => 'required|exists:categories,id',
            'poet_id' => 'required|exists:poets,id',
            'alphabit'=> 'nullable|exists:alphabets,name',
        ]);

        $poetry = new Poetries();
        $poetry->user_id   = Auth::id();
        $poetry->title     = $request->title;
        $poetry->poet_id   = $request->poet_id;
        $poetry->cat_id    = $request->cat_id;
        $poetry->alphabit  = $request->alphabit;
        $poetry->body      = $request->body;
        $poetry->date      = date('Y-m-d');
        $poetry->save();

        session()->flash('msg', 'Poetry added successfully!');
        return redirect()->route('poets.show', $request->poet_id);
    }

    /**
     * Show form to create a new poetry (specific category with subcategories)
     */
    public function poetryCreate($id)
    {
        $ids = explode('-', $id);
        $cat_id = $ids[0];
        $poet_id = $ids[1];

        $poet = Poet::findOrFail($poet_id);
        $category = Category::findOrFail($cat_id);
        $subCategories = SubCategory::where('category_id', $cat_id)->get();
        $alphabits = Alphabet::all();

        return view('back-end.poets.poetries.poetry-create', compact('poet', 'category', 'subCategories', 'alphabits', 'cat_id', 'poet_id'));
    }

    /**
     * Store a new poetry (specific category)
     */
    public function poetryStore(Request $request)
    {
        $request->validate([
            'title'   => 'required',
            'body'    => 'required',
            'cat_id'  => 'required|exists:categories,id',
            'poet_id' => 'required|exists:poets,id',
            'alphabit'=> 'nullable|exists:alphabets,name',
        ]);

        $poetry = new Poetries();
        $poetry->user_id   = Auth::id();
        $poetry->title     = $request->title;
        $poetry->poet_id   = $request->poet_id;
        $poetry->cat_id    = $request->cat_id;
        $poetry->scat_id   = $request->scat_id; // optional
        $poetry->alphabit  = $request->alphabit;
        $poetry->body      = $request->body;
        $poetry->date      = date('Y-m-d');
        $poetry->save();

        session()->flash('msg', 'Poetry added successfully!');
        return redirect()->route('poets.show', $request->poet_id);
    }

    /**
     * Show form to edit a poetry.
     */
    public function poetryEdit($id)
    {
        $poetry = Poetries::with(['poet', 'category'])->findOrFail($id);
        $categories = Category::all();
        $alphabits = Alphabet::all();
        $subCategories = SubCategory::where('category_id', $poetry->cat_id)->get();
         $poet = Poet::findOrFail($poetry->poet_id);

        return view('back-end.poets.poetries.poetry-create-all', compact('poetry', 'categories', 'alphabits', 'subCategories','poet'));
    }

    /**
     * Update a poetry.
     */
    public function poetryUpdate(Request $request, $id)
    {
        $request->validate([
            'title'   => 'required',
            'body'    => 'required',
            'cat_id'  => 'required|exists:categories,id',
            'alphabit'=> 'nullable|exists:alphabets,name',
        ]);

        $poetry = Poetries::findOrFail($id);
        $poetry->title    = $request->title;
        $poetry->cat_id   = $request->cat_id;
        $poetry->scat_id  = $request->scat_id;
        $poetry->alphabit = $request->alphabit;
        $poetry->body     = $request->body;
        $poetry->save();

        session()->flash('msg', 'Poetry updated successfully!');
        return redirect()->route('poets.show', $poetry->poet_id);
    }

    /**
     * Delete a poetry.
     */
    public function poetryDelete($id)
    {
        $poetry = Poetries::findOrFail($id);
        $poetry->delete();
        session()->flash('msg', 'Poetry deleted!');
        return back();
    }

    /**
     * Show form to edit a poet.
     */
    public function edit(Poet $poet)
    {
        $centries = Centry::all();
        return view('back-end.poets.edit', compact('poet', 'centries'));
    }

    /**
     * Update a poet.
     */
    public function update(Request $request, Poet $poet)
    {
        $request->validate([
            'name'      => 'required|max:255',
            'bio'       => 'required',
            'address'   => 'required',
            'centry_id' => 'required|exists:centries,id',
            'image'     => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $poet->name         = $request->name;
        $poet->last_name    = $request->last_name;
        $poet->father_name  = $request->father_name;
        $poet->centry_id    = $request->centry_id;
        $poet->address      = $request->address;
        $poet->email        = $request->email;
        $poet->dob          = $request->dob;
        $poet->phone        = $request->phone;
        $poet->bio          = $request->bio;

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

        $poet->save();
        session()->flash('msg', 'Poet updated successfully!');
        return redirect()->route('poets.index');
    }

    /**
     * Delete a poet.
     */
    public function delete(Poet $poet)
    {
        $poet->delete();
        session()->flash('msg', 'Poet deleted!');
        return back();
    }

    /**
     * Display a report of poets and their poetries.
     */
    public function report()
    {
        $totalPoets = Poet::count();
        $poetsWithPoetries = Poet::has('poetries')->count();
        $poetsWithoutPoetries = Poet::doesntHave('poetries')->count();

        $byCentury = Poet::select('centry_id', DB::raw('count(*) as total'))
                        ->with('centry')
                        ->groupBy('centry_id')
                        ->get();

        $topPoets = Poet::withCount('poetries')
                        ->orderBy('poetries_count', 'desc')
                        ->limit(10)
                        ->get();

        return view('back-end.poets.report', compact('totalPoets', 'poetsWithPoetries', 'poetsWithoutPoetries', 'byCentury', 'topPoets'));
    }
}
