<?php

namespace App\Http\Controllers\Backend;

use App\Helpers\CoreConstants;
use App\Http\Controllers\Controller;
use App\Models\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class MenuController extends Controller
{
    public function index()
    {
        $data['PageTitle'] = 'All Menu';
        $data['menus'] = Menu::whereNull('parent_id')
            ->with('submenus')
            ->orderBy('order')
            ->get();

        $data['parentMenuShowClass'] = 'show';
        $data['allMenuActiveClass']  = 'active';

        return view('backend.menu.index')->with($data);
    }

    public function create()
    {
        $data['PageTitle'] = 'Add Menu';
        $data['menus'] = Menu::all();
        $data['parentMenuShowClass']  = 'show';
        $data['createMenuActiveClass'] = 'active';

        return view('backend.menu.create')->with($data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'menu_name' => 'required|string|max:255',
            'parent_id' => 'nullable|exists:menus,id',
            'order'     => 'nullable|integer',
        ]);

        $slug = Str::slug($request->menu_name, '-');

        $menu_item = new Menu();
        $menu_item->name      = $request->menu_name;
        $menu_item->slug      = $slug;
        $menu_item->parent_id = $request->parent_id;
        $menu_item->order     = $request->order ?? 0;

        if ($request->hasFile('image')) {
            $image       = $request->file('image');
            $original    = time() . '.' . $image->getClientOriginalName();
            $fileName    = pathinfo($original, PATHINFO_FILENAME);
            $extension   = pathinfo($original, PATHINFO_EXTENSION);
            $imageName   = preg_replace('/\s+/', '', $fileName);
            $file_name   = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
            $name        = $file_name . '.' . $extension;
            $store       = $image->storeAs('upload', $name, 'public');

            $menu_item->image = $store;
        }

        $menu_item->save();

        return redirect()
            ->route('admin.menu-item.index')
            ->with('success', CoreConstants::CREATED_SUCCESSFULLY);
    }

    public function edit($id)
    {
        $data['PageTitle'] = 'Edit Menu';
        $data['menu'] = Menu::whereNull('parent_id')->findOrFail($id);
        $data['parentMenuShowClass']  = 'show';
        $data['createMenuActiveClass'] = 'active';

        return view('backend.menu.edit')->with($data);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'menu_name' => 'required|string|max:255',
            'order'     => 'nullable|integer',
        ]);

        $menu = Menu::whereNull('parent_id')->findOrFail($id);
        $slug = Str::slug($request->menu_name, '-');

        $menu->name  = $request->menu_name;
        $menu->slug  = $slug;
        $menu->order = $request->order ?? 0;

        if ($request->hasFile('image')) {
            $image       = $request->file('image');
            $original    = time() . '.' . $image->getClientOriginalName();
            $fileName    = pathinfo($original, PATHINFO_FILENAME);
            $extension   = pathinfo($original, PATHINFO_EXTENSION);
            $imageName   = preg_replace('/\s+/', '', $fileName);
            $file_name   = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
            $name        = $file_name . '.' . $extension;
            $store       = $image->storeAs('upload', $name, 'public');

            if ($menu->image && Storage::disk('public')->exists($menu->image)) {
                Storage::disk('public')->delete($menu->image);
            }

            $menu->image = $store;
        }

        $menu->save();

        return redirect()
            ->route('admin.menu-item.index')
            ->with('success', CoreConstants::UPDATED_SUCCESSFULLY);
    }

    public function destroy($id)
    {
        $menu = Menu::whereNull('parent_id')->findOrFail($id);

        if ($menu->image && Storage::disk('public')->exists($menu->image)) {
            Storage::disk('public')->delete($menu->image);
        }

        $menu->delete();

        return redirect()
            ->route('admin.menu-item.index')
            ->with('success', CoreConstants::DELETED_SUCCESSFULLY);
    }

    // ---------- Submenu related functions ----------

    public function subindex()
    {
        $data['PageTitle'] = 'Submenus';

        $data['menu']  = Menu::whereNotNull('parent_id')->get();
        $data['menus'] = Menu::whereNull('parent_id')->get();

        $data['parentMenuShowClass']  = 'show';
        $data['allSubMenuActiveClass'] = 'active';

        return view('backend.menu.submenu')->with($data);
    }

    public function subedit($id)
    {
        $data['PageTitle'] = 'Submenus';
        $data['menu']      = Menu::findOrFail($id);
        $data['mainMenus'] = Menu::whereNull('parent_id')->get();

        $data['parentMenuShowClass']  = 'show';
        $data['allSubMenuActiveClass'] = 'active';

        return view('backend.menu.edit-submenu')->with($data);
    }

    public function subUpdate(Request $request, $id)
    {
        $submenu = Menu::whereNotNull('parent_id')->findOrFail($id);

        $request->validate([
            'menu_name' => 'required|string|max:255',
            'order'     => 'required|integer',
            'parent_id' => 'required|exists:menus,id',
        ]);

        $slug = Str::slug($request->menu_name, '-');

        $submenu->name      = $request->menu_name;
        $submenu->order     = $request->order;
        $submenu->slug      = $slug;
        $submenu->parent_id = $request->parent_id;

        if ($request->hasFile('image')) {
            $image       = $request->file('image');
            $original    = time() . '.' . $image->getClientOriginalName();
            $fileName    = pathinfo($original, PATHINFO_FILENAME);
            $extension   = pathinfo($original, PATHINFO_EXTENSION);
            $imageName   = preg_replace('/\s+/', '', $fileName);
            $file_name   = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
            $name        = $file_name . '.' . $extension;
            $store       = $image->storeAs('upload', $name, 'public');

            if ($submenu->image && Storage::disk('public')->exists($submenu->image)) {
                Storage::disk('public')->delete($submenu->image);
            }

            $submenu->image = $store;
        }

        $submenu->save();

        return redirect()
            ->route('admin.submenu')
            ->with('success', CoreConstants::UPDATED_SUCCESSFULLY);
    }

    public function subDestroy($id)
    {
        $menu = Menu::whereNotNull('parent_id')->findOrFail($id);

        if ($menu->image && Storage::disk('public')->exists($menu->image)) {
            Storage::disk('public')->delete($menu->image);
        }

        $menu->delete();

        return redirect()
            ->route('admin.submenu')
            ->with('success', CoreConstants::DELETED_SUCCESSFULLY);
    }
}
