<?php

namespace Mamad\Page\Http\Controllers;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Mamad\Article\Repositories\ArticleRepository;
use Mamad\Category\Repositories\CategoryRepository;
use Mamad\Page\Http\Requests\AddPageRequest;
use Mamad\Page\Http\Requests\EditPageRequest;
use Mamad\Page\Models\Page;
use Mamad\Page\Repository\PageRepository;
use Mamad\PostMeta\Repository\PostMetaRepository;
use Mamad\Product\Repository\ProductRepository;
use Mamad\ThemeSetting\Repository\ThemeSettingRepository;
use Mehrab\Service\Repositories\ServiceRepo;

class PageController extends Controller
{
    //theme functions

    public function index($slug)
    {

        $page=PageRepository::find_by_slug($slug);
        if($page){
            $data=[];
            if(view()->exists("Front::page-".$slug)){
                $view="Front::page-".$slug;
            } else{
                $view="Front::page";
            }

            if($slug=="contact-us"){
                $data=ThemeSettingRepository::getOption("contact_us")[0];
            }

            if($slug=="services"){
                $data=resolve(ServiceRepo::class)->all_Parent_active();
            }
            if($slug=="blog"){
                $data=ArticleRepository::getPublished();;
            }

            return view($view,["page"=>$page,"data"=>$data]);
        }
        return abort(404);
    }

    //admin functions
    public function list_page(Request $request){
        $this->authorize("index",Page::class);
        $pages=PageRepository::order_page($request->orderBy);
        return view("Page::Admin.page_list",["pages"=>$pages]);
    }

    public function add_page_form (){
        $this->authorize("create",Page::class);
        return view("Page::Admin.page_add");
    }

    public function add_page(AddPageRequest $request)
    {
        $this->authorize("create",Page::class);
        $slug=make_slug_for_data($request->title,$request->slug);

        $request->request->add(["slug"=>$slug]);

        $pageId=PageRepository::create($request);
        PostMetaRepository::update_meta_tag($pageId,$request);
        return redirect()->route("admin_edit_page",["id"=>$pageId->id]);
    }
    public function edit_page_form($id)
    {
        $this->authorize("edit",Page::class);
        $page=PageRepository::find($id);


        return view("Page::Admin.page_edit",["page"=>$page]);
    }

    public function edit_page (EditPageRequest $request)
    {
        $this->authorize("update",Page::class);
        $slug=make_slug_for_data($request->title,$request->slug);

        $request->request->add(["slug"=>$slug]);

        $page=PageRepository::find($request->id);
        PostMetaRepository::update_meta_tag($page,$request);
        PageRepository::update($page,$request);
        return back();
    }
    public function delete_page($id)
    {
        $this->authorize("delete",Page::class);
        PageRepository::destroy($id);
        return back();
    }

}
