<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Common\CommonLib;
use App\Common\FileManager;
use App\Common\DatabaseQuery;
use App\Interfaces\Admin\AdminMenuPagesInterface;
use App\MenuPage;
use Illuminate\Support\Facades\Auth;
use View;
use Session;
use Redirect;
use Lang;

class MenuPagesController extends Controller
{
    private $image_path = 'assets/files/pages';

    // constructor
    public function __construct(AdminMenuPagesInterface $menu_pages)
    {
        $this->clib = new CommonLib;
        $this->db = new DatabaseQuery;
        $this->fmanager = new FileManager;
        $this->menu_pages = $menu_pages;

    }

    public function index()
    {
        // get data
        $this->data['menu_pages'] = $this->menu_pages->getAdminMenuPages();
        // return
        return View::make('admin.menu_pages.index', ['data' => $this->data]);
    }

    public function create(){
        $menupages = MenuPage::all()->pluck('title_ba','id');
        return view('admin.menu_pages.create',compact('menupages'));
    }

      public function store(Request $request)
    {
        // declarations
        $skip = [];
        // init validation
        $rules = [
            'title_ba' => 'required'
        ];

        // check if all ok. null mean do not touch Input
        if ($request->validate($rules)) {
            // get post data
            $data = $_POST;
            // upload file(s) if validation ok
            $files = $this->fmanager->formUpload($this->image_path);
            // validate file upload
            if (!$this->fmanager->validate($files)) {
                return Redirect::back()->withInput()->with('error', Lang::get('admin.file_upload_fails'));
            }
            // add to array for db manipulation
            $this->fmanager->toDataArray($data, $files);
            // generate unique slug
            $data['slug'] = $this->clib->checkSlug('menu_pages', 'slug', $this->clib->makeSlug($_POST['title_ba']),false,$data['pid']);
            // check if category empty then no parent selected
            if ($data['pid'] == '') {
                $data['pid'] = 0;
            }
            $data['created_by'] = Auth::user()->id;
            $data['updated_by'] = Auth::user()->id;
            // if file canceled the input exist so it's needed to be removed from post list
            $data = $this->clib->postToDB($data, $skip);
            // execute
            if (MenuPage::create($data)) {
                Session::flash('success', Lang::get('admin.db_success'));
                return Redirect::back();
            } else {
                Session::flash('errors', Lang::get('admin.db_fails'));
            }
        }
        // return
        //return Redirect::back()->withErrors($v->validator())->withInput();
    }
}
