<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\NavigationSections;
use App\Navigations;
use App\Pages;
use Illuminate\Support\Facades\Auth;
use App\Helpers\NavHelpers;
use App\Http\Controllers\AdminController;

class NavigationsController extends AdminController {

    public function __construct() {
        $this->middleware('auth');

        $this->breadcrumbs = $this->getBreadcrumbs();
        $this->breadcrumbs[1]['link'] = "admin/navigations";
        $this->breadcrumbs[1]['name'] = "Navigation Sections";
    }

    public function index() {


        $model = NavigationSections::orderBy("PKSectionID", "desc")->get();
        $data["pageHeader"] = false;
        $data["title"] = "Navigation Sections";
        $data["SubTitle"] = "List";
        $data["model"] = $model;
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/navigations/index', $data);
    }

    public function create() {

        $model = new NavigationSections();

        $data["pageHeader"] = false;
        $data["title"] = "Navigation";
        $data["SubTitle"] = "List";
        $data["model"] = $model;

        $pagesModel = Pages::where("Status", "Enabled")->get();

        $pages = array();
        foreach ($pagesModel as $pageModel) {
            $pages[$pageModel->PKPageID]["ID"] = $pageModel->PKPageID;
            $pages[$pageModel->PKPageID]["AccessURL"] = $pageModel->AccessURL;
            $pages[$pageModel->PKPageID]["Title"] = $pageModel->Title;
        }

        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Create";
        $data["navigations"] = array();
        $data["pages"] = $pages;
        $data["breadcrumbs"] = $this->breadcrumbs;

        return view('admin/navigations/create', $data);
    }

    public function save(Request $request) {
        $rules = [
            'Title' => 'required|string',
//            'p_id' => 'required'
        ];

        $input = $request->all();

        $message = ["p_id.required" => "please add pages."];
        $validator = Validator::make($input, $rules, $message);
        //$validator->errors()->add('pages', 'Something is wrong with this field!');


        if ($validator->fails()) {
//            $errors = $validator->errors();
//            $response['errors'] = $errors;
//            $header = 402;
            //return response()->json($response, 402);
                        return redirect()->back()->withErrors($validator->errors())->withInput();

        } else {

//            $ids = $input["p_id"];
//            $titles = $input["p_text"];
//            $urls = $input["p_url"];
//            $pagetype = $input["p_link"];
            
            $links = $input["links"];
            $links = json_decode($links, true);
            unset($input["LinkWith"]);
            unset($input["LinkWithURL"]);
            
            $ids=array();
            $titles=array();
            $urls=array();
            $pagetype=array();

            unset($input["Template"]);
            unset($input["links"]);
            unset($input["_token"]);
            unset($input["pages"]);
            unset($input["p_id"]);
            unset($input["p_text"]);
            unset($input["p_url"]);
            unset($input["nav_label"]);
            unset($input["assigned_output"]);
            unset($input["title"]);
            unset($input["urls"]);
            unset($input["p_pagetype"]);
            unset($input["p_link"]);
            unset($input["nav_url"]);


            $input["CreatedDateTime"] = date("Y-m-d H:i:s");
            $input["CreatedBy"] = Auth::user()->id;
            $input["FKWebsiteID"] = 1;
            $response["id"] = NavigationSections::insertGetId($input);

            $this->insertNavigations($response["id"], $ids, $titles, $urls, $pagetype, $links);


            $response["message"] = "Navigation added successfully!";
            $header = 200;
        }
        return redirect('admin/navigations');

//        return response()->json($response, $header);
    }

    public function edit($id) {


        $model = NavigationSections::find($id);

        $pagesModel = Pages::where("Status", "Enabled")->get();



        $pages = array();
        foreach ($pagesModel as $pageModel) {
            $pages[$pageModel->PKPageID]["ID"] = $pageModel->PKPageID;
            $pages[$pageModel->PKPageID]["AccessURL"] = $pageModel->AccessURL;
            $pages[$pageModel->PKPageID]["Title"] = $pageModel->Title;
        }
        $navigations = array();

        $parentModel = Navigations::where("ParentID", 0)
                ->where("FKSectionID", $id)
                ->get();
        $i = 0;
        foreach ($parentModel as $m) {


            $navigations[$i]["name"] = $m->Name;
            $navigations[$i]["id"] = $m->PKNavigationID;
            $navigations[$i]["url"] = $m->LinkWithURL;
            $navigations[$i]["type"] = $m->LinkWith;

            $childrenModel = Navigations::where("ParentID", $m->PKNavigationID)
                    ->where("FKSectionID", $id)
                    ->get();

            if (count($childrenModel) > 0) {
                $children = array();
                $j = 0;
                foreach ($childrenModel as $c) {
                    $children[$j]["name"] = $c->Name;
                    $children[$j]["id"] = $c->PKNavigationID;
                    $children[$j]["url"] = $c->LinkWithURL;
                    $children[$j]["type"] = $c->LinkWith;
                    $j++;
                }
                //d($children,1);

                $navigations[$i]["children"] = $children;
            } else {
                $navigations[$i]["children"] = [];
                // $navigations[$i]["children"]= json_encode($navigations[$i]["children"]);
            }
            $i++;
        }

        if (!empty($model->LinkWithURL) && !empty($model->LinkWith)) {
            $model["Template"] = "has_no_child";
        } else {
            $model["Template"] = "has_child";
        }

        $data["navigations"] = $navigations;
        $data["model"] = $model;
        $data["pageHeader"] = false;
        $data["title"] = "Navigation";
        $data["SubTitle"] = "Edit";
        $data["pages"] = $pages;

        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Edit";

        $data["breadcrumbs"] = $this->breadcrumbs;

        return view('admin/navigations/edit', $data)->with('id', $id);
    }

    public function update($id, Request $request) {

        $rules = [
            'Title' => 'required|string',
//            'p_id' => 'required'
        ];


        $input = $request->all();

        $message = ["p_id.required" => "please add pages."];
        $validator = Validator::make($input, $rules, $message);


        if ($validator->fails()) {
//            $errors = $validator->errors();
//            $response['errors'] = $errors;
//            $header = 402;
            //return response()->json($response, 402);
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
            $links = $input["links"];
            $links = json_decode($links, true);





            $ids = array();
            $titles = array();
            $urls = array();
            $pagetype = array();
            unset($input["Template"]);

            unset($input["links"]);

            unset($input["_token"]);
            unset($input["pages"]);
            unset($input["p_id"]);
            unset($input["p_text"]);
            unset($input["p_url"]);
            unset($input["nav_label"]);
            unset($input["assigned_output"]);
            unset($input["title"]);
            unset($input["urls"]);
            unset($input["p_pagetype"]);
            unset($input["p_link"]);
            unset($input["nav_url"]);

            $input["UpdatedDateTime"] = date("Y-m-d H:i:s");
            $input["UpdatedBy"] = Auth::user()->PKUserID;

            NavigationSections::where("PKSectionID", $id)->update($input);

            Navigations::where("FKSectionID", $id)->delete();


            $this->insertNavigations($id, $ids, $titles, $urls, $pagetype, $links);


            $response["message"] = "Navigation added successfully!";
            $header = 200;
        }
//        return response()->json($response, $header);
        return redirect('admin/navigations');
    }

    public function insertNavigations($id, $pageIds, $titles, $urls, $link, $links) {

        if (!empty($links)) {
            $insert = array();
            $i = 0;
            foreach ($links as $val) {
                $insert = array();

                $insert["Name"] = $val["name"];
                $insert["LinkWithURL"] = $val["url"];
                $insert["FKSectionID"] = $id;
                $insert["Position"] = $i;
                $linkWith = $val["type"];
                $insert["LinkWith"] = $linkWith;
                $insert["FKPageID"] = 0;
                $navId = Navigations::insertGetId($insert);

                if (!empty($val["children"])) {
                    $insert = array();
                    $j = 0;
                    foreach ($val["children"] as $child) {

                        $insertChild = array();
                        $insertChild["Name"] = $child["name"];
                        $insertChild["LinkWithURL"] = $child["url"];
                        $insertChild["FKSectionID"] = $navId;
                        $insertChild["FKSectionID"] = $id;
                        $insertChild["ParentID"] = $navId;
                        $insertChild["Position"] = $j;
                        $linkWith = $child["type"];
                        $insertChild["LinkWith"] = $linkWith;
                        $insertChild["FKPageID"] = 0;
                        $childId = Navigations::insertGetId($insertChild);
                        $j++;
                    }
                }

                $i++;
            }
        }
    }

    public function show($id) {

        $model = NavigationSections::find($id);

        $data["model"] = $model;
        $data["pageHeader"] = false;
        $data["title"] = "Location (" . $model->Title . ")";
        $data["SubTitle"] = "View";

        $data["navigations"] = $model->navigations;

        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = $model->Title;

        $data["breadcrumbs"] = $this->breadcrumbs;

        return view('admin/navigations/show', $data)->with('id', $id);
    }

    public function delete($id) {

        NavigationSections::where("PKSectionID", $id)->delete();
        Navigations::where("FKSectionID", $id)->delete();
        \Session::flash('error', 'Navigation deleted successfully!');
        return redirect('admin/navigations');
    }

}
