<?php

namespace App\Http\Controllers\Admin\Api;

use App\Http\Controllers\Controller;
use App\Models\Page;
use App\libs\Response\GlobalApiResponse;
use App\libs\Response\GlobalApiResponseCodeBook;
use App\Services\Admin\PageService;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    private $pageService;

    public function __construct(PageService $pageService) {
        $this->pageService = $pageService;
    }

    public function pagesList(){
        $data = $this->pageService->pagesList();
        return (new GlobalApiResponse())->success('Pages list',1,$data);
    }

    public function getPageDetail($id){
        $data = $this->pageService->getPageDetail($id);
        return (new GlobalApiResponse())->success('Pages Details',1,$data);
    }

    public function createPage(Request $request){
        $this->pageService->createPage($request->all());
        if($this->pageService->hasError()) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, $this->pageService->getErrors()[0]['message'], $this->pageService->getErrors());
        }
        return (new GlobalApiResponse())->success('Page successfully created');
    }

    public function updatePage(Request $request, $id){
        $this->pageService->updatePage($request->all(), $id);
        if($this->pageService->hasError()) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, $this->pageService->getErrors()[0]['message'], $this->pageService->getErrors());
        }
        return (new GlobalApiResponse())->success('Page successfully updated');
    }

    public function deletePage(Request $request){
        if (empty($request->page_ids)) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, "IDs not found!");
        }
        Page::whereIn('id', $request->page_ids)->delete();
        return (new GlobalApiResponse())->success("Page successfully deleted");
    }

    public function updatePageStatus(Request $request)
    {
        if (empty($request->page_ids)) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, "IDs not found!");
        }
        $mods = Page::whereIn('id', $request->page_ids)->get();
        if ($mods) {
            foreach ($mods as $mod) {
                $mod->update([$request->column => $request->status]);
            }
            return (new GlobalApiResponse())->success("Status successfully updated");
        } else {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::RECORD_NOT_EXIST, "Page not found!");
        }
    }
}
