<?php

namespace App\Http\Controllers\Dashboard;

use App\Helpers\Alert;
use App\Http\Requests\Dashboard\CategoryRequest;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class CategoriesController extends Controller
{
    public function index()
    {
        return view("dashboard.categories.index")->with([
            "categories" => Category::all()
        ]);
    }

    public function create()
    {
        return view("dashboard.categories.create");
    }

    public function editShow($id)
    {
        return view("dashboard.categories.edit")->with([
            "category" => Category::findOrFail($id)
        ]);
    }

    public function edit(CategoryRequest $request, $id)
    {
        $category = Category::findOrFail($id);

        $category->name = $request->name;
        $category->color = $request->color;

        $category->save();

        Alert::flash("Category edited successfully");

        return redirect()->route("dashboard.categories.index");
    }

    public function store(CategoryRequest $request)
    {
        $category = new Category();

        $category->name = $request->name;
        $category->color = $request->color;

        $category->save();

        Alert::flash("New category added successfully");

        return redirect()->route("dashboard.categories.create");
    }

    public function block(Request $request, $id)
    {
        $category = Category::find($id);
        $posts = Post::where("category_id", $id)->get();

        foreach ($posts as $post) {
            $post->is_active = false;
            $post->save();
        }

        $category->is_active = false;
        $category->save();


        Alert::flash($category->name . " blocked successfully");

        return redirect()->route("dashboard.categories.index");
    }

    public function unblock(Request $request, $id)
    {
        $category = Category::find($id);
        $posts = Post::where("category_id", $id)->get();

        foreach ($posts as $post) {
            $post->is_active = true;
            $post->save();
        }

        $category->is_active = true;
        $category->save();

        Alert::flash($category->name . " unblocked successfully");

        return redirect()->route("dashboard.categories.index");
    }

    public function destroy(Request $request, $id)
    {
        $category = Category::find($id);

        if (Post::where("category_id", $id)->count() > 0) {

            $posts = Post::where("category_id", $id)->get();

            foreach ($posts as $post) {
                $post->category()->dissociate($category);
                Storage::disk('uploads')->delete($post->image_link);
                $post->delete();
            }
        }

        $category->delete();

        Alert::flash($category->name . " deleted successfully");

        return redirect()->route("dashboard.categories.index");
    }
}
