<?php

namespace App\Http\Controllers;

use App\Models\Meta;
use App\Models\Node;
use App\Models\Log;
use App\Models\Subject;
use App\Models\EbookVolume;
use App\Models\Indexing;
use App\Models\Journal;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Auth;
use DB;
use File;

class IndexingController extends BenthamController
{

    public function index(Request $request)
    {
        $editPermission   = false;
        $deletePermission = false;
        $createPermission = false;
        $search  = $request->get('search');

        if (checkPermission('IndexingAgencies', 'create')) {
            $createPermission = true;
        }
        if (checkPermission('IndexingAgencies', 'edit')) {
            $editPermission = true;
        }
        if (checkPermission('IndexingAgencies', 'delete')) {
            $deletePermission = true;
        }
        $indexing_list = Indexing::getAllIndexing($search);

        return view('admin.indexing_agencies.indexing', ['indexing_list' => $indexing_list, 'createPermission' => $createPermission, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission, 'createPermission' => $createPermission]);
    }

    public function create(Request $request)
    {
        $temp = rtrim(Indexing::display_parent(), '_');
        $option = explode('_', $temp);
        $arr = array();
        if ($temp != '') {
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $arr[0] = 'Please Select';
                    $arr[$id] = $name;
                }
            }
        } else {
            $arr[0] = 'Please Select';
        }
        return view('admin.indexing_agencies.indexing_add', with(['indexing_list' => $arr]));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        } else {

            // try transaction start here for data integrity
            try {

                DB::beginTransaction();

                $user = Auth::user();
                $data = array(
                    'parent_id'           => trim($request->get('indexing')),
                    'title'              => trim($request->get('title')),
                    'description'        => trim($request->get('description')),
                    'sequence_no'           => trim($request->get('sequence')),
                    'created_on'         => time(),
                    'created_by'         => $user->id,
                    'updated_on'         => time(),
                    'updated_by'         => $user->id,
                    'ip'                 => ip2long($request->ip()),
                );
                $indexing_id['id'] = Indexing::AddIndexingAgencies($data);

                $add_log = array(
                    'content_id'      => $indexing_id['id'],
                    'content_type_id' => config('constants.log_content_types.IndexingAgencies'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($data),
                    'created_dated'   => time(),
                    'created_by'      => $user->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return  Redirect::back();
            }
            return redirect()->route('indexing_agencies.index')->with('success', 'Indexing was added.');
        }
    }

    public function edit($id)
    {
        $indexing_list = Indexing::GetIndexingbyID($id);

        $temp = rtrim(Indexing::display_parent(), '_');
        $option = explode('_', $temp);
        $arr = array();
        if ($temp != '') {
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $arr[0] = 'Please Select';
                    $arr[$id] = $name;
                }
            }
        } else {
            $arr[0] = 'Please Select';
        }

        return view('admin.indexing_agencies.indexing_edit', with(['indexing_list' => $indexing_list, 'indexing' => $arr]));
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        } else {

            // try transaction start here for data integrity
            try {

                DB::beginTransaction();

                $user = Auth::user();
                $data = array(
                    'parent_id'          => trim($request->get('indexing')),
                    'title'              => trim($request->get('title')),
                    'description'        => trim($request->get('description')),
                    'sequence_no'        => trim($request->get('sequence')),
                    'updated_on'         => time(),
                    'updated_by'         => $user->id,
                    'ip'                 => ip2long($request->ip()),
                );
                $indexing_list = Indexing::UpdateIndexingbyID($data, $id);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return  Redirect::back();
            }
            return redirect()->route('indexing_agencies.index')->with('success', 'Indexing has been updated.');
        }
    }

    public function destroy(Request $request, $id)
    {
        $user     = Auth::user();
        $data = array(
            'status'             => 0,
            'updated_on'         => time(),
            'updated_by'         => $user->id,
            'ip'                 => ip2long($request->ip()),
        );

        $indexing_agencies = Indexing::CheckParentChildbyID($id);
        if(empty($indexing_agencies)){
        $indexing_agencies = Indexing::UpdateIndexingbyID($data, $id);
        return redirect()->route('indexing_agencies.index')->with('success', 'Indexing has been deleted successfully.');
        }else{
            return redirect()->route('indexing_agencies.index')->with('error', 'Indexing has not been deleted because their child exists.');
        }
    }

    public function BrowsebyJournalIndexing()
    {
        $indexing_agencies = array();

        $indexing_list = Indexing::GetIndexingJournal();
        // dd($indexing_list);
        if ($indexing_list) {
            $indexing_agencies = $this->getresultTree($indexing_list);
        }
        // dd($indexing_agencies);
        $journal = Indexing::GetIndexingJournalDetails();
        // dd($journal);

        return view('pages', with(['page_name' => 'indexing-agencies', 'indexing_list' => $indexing_agencies, 'journal_list' => $journal]));
    }

    public function BrowsebyEbookIndexing(){

        $indexing_agencies = array();

        $indexing_list = Indexing::GetIndexingEbook();
        // dd($indexing_list);
        if ($indexing_list) {
            $indexing_agencies = $this->getresultTree($indexing_list);
        }
        // dd($indexing_agencies);
        $ebook = Indexing::GetIndexingEbookDetails();
        // dd($ebook);

        return view('pages', with(['page_name' => 'indexing-agencies-books', 'indexing_list' => $indexing_agencies, 'ebook_list' => $ebook]));
    }

    public function getresultTree(array $elements, $parentId = 0)
    {
        $branch = array();
        foreach ($elements as $element) {
            if ($element->parent_id == $parentId) {

                $children = $this->getresultTree($elements, $element->index_id);
                if ($children) {

                    $element->child = $children;
                }
                $branch[] = $element;
            }
        }
        $keys = array_column($branch, 'sequence_no');

        array_multisort($keys, SORT_ASC, $branch);

        return $branch;
    }

}
