<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\PagesModel;
use Illuminate\Http\Request;

class PageController extends Controller
{
    public function pages()
    {
        $records   =  PagesModel::get();
        return view('backend.pages.list', compact('records'));
    }

    public function addPage($id = '')
    {
        $record = '';
        if ($id > 0) {
            $record = PagesModel::Where('id', $id)->first();
        }
        return view('backend.pages.add_edit', compact('record'));
    }

    public function storeUpdatePage(Request $request)
    {
        $input     = $request->all();
        $id        = isset($input['id']) ? $input['id'] : 0;

        $dataArr = [];
        foreach ($input as $key => $val) {
            if ($key != '_token' && $key != 'id' )
                $dataArr[$key] = $val;
        }

       
        if ($id == 0 || $id == '') {
            $request->validate([
                'type'          =>  "required|unique:pages,type",
                'title'          =>  "required|unique:pages,title",
                'content'          =>  "required",
              
            ]);
           $insert = PagesModel::create($dataArr);
           if($insert['id'] > 0)
           {
               return redirect()->route('pages')->with('success', 'Pages Saved Successfully');
           }else{
               return redirect()->route('pages')->with('error', 'Something went wrong!');
           }
           
        } else {
            $request->validate([
                 'type'          =>  "required",
                'title'          =>  "required",
                'content'        =>  "required",              
            ]);
            $update = PagesModel::Where('id',$id)->update($dataArr);
            return redirect()->route('pages')->with('success', 'Pages Updated Successfully');;
        }        
    }
}
