<?php

namespace App\Http\Controllers\Backend\Pages;

use App\Http\Controllers\Controller;
use App\Models\ComponentMaster;
use App\Models\Page;
use App\Services\Pages\PagesService;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $pages = Page::orderByDesc('id')->get();
        return view('backend.pages.pages.index', compact('pages'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $components = ComponentMaster::orderBydesc('id')->with('componentFiled')->get();

        return view('backend.pages.pages.create', compact('components'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        PagesService::create(request()->all());
        return redirect()->back()->with('success', 'Page create successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $components = ComponentMaster::orderBydesc('id')->with('componentFiled')->get();

        $page = Page::where('id', $id)->with('component')->first();

        return view('backend.pages.pages.edit', compact('components', 'page'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {

        PagesService::Update(request()->all(), $id);
        return redirect()->back()->with('success', 'Page Update successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $page =   Page::where('id', $id)->first();
        if ($page->image) {
            unlink('images/' . $page->image);
        }
        $page->delete();
        return redirect()->back()->with('success', 'Page Delete successfully');
    }
    public function addui()
    {

        PagesService::PagesUI(request()->all());
        $info = ComponentMaster::where('id', request()->id)->first();
        $additem = ['id' => request()->id, 'name' => $info->name, 'display' => request()->display];
        $components = ComponentMaster::orderBydesc('id')->with('componentFiled')->get();
        return response()->json(['component' => $components, 'item' => $additem]);
    }
}