<?php

namespace App\Http\Controllers;

use App\Models\Journal;
use App\Models\Log;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Volume;
use App\Models\Issue;
use DB;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;

class VolumeController extends BenthamController
{

    public function index(Request $request)
    {
        $editPermission   = false;
        $deletePermission = false;

        $param['journal_id'] = $journal_id = $request->get('journal_id');
        $param['volume_id']  = $volume_id  = $request->get('volume_id');
        $param['year_id']    = $year_id    = $request->get('year_id');

        $frm_search = $request->get('frm_search');
        $ajx_search = $request->get('ajx_search');

        if ($frm_search != null && $frm_search == true) {

            $volume_list     = Volume::GetVolume($param);
            $p['journal_id'] = $journal_id;
            $volume_search   = Volume::GetVolumeTitleById($p);

        }

        if ($ajx_search != null && $ajx_search == true) {
            if (!empty($journal_id)) {
                $p['journal_id'] = $journal_id;
                $volume_search   = Volume::GetVolumeTitleById($p);
                return response()->json(array('volume_search' => $volume_search), 200);
            }
        }

        if ($frm_search == null && $ajx_search == null) {
            $volume_search = array();
            $year_search   = array();
            $volume_list   = Volume::GetVolume();
        }

        $journal_search = Journal::GetJournalTitle();
        $year_search    = Journal::GetYear();

        if (checkPermission('volume', 'edit')) {
            $editPermission = true;
        }if (checkPermission('volume', 'delete')) {
            $deletePermission = true;
        }

        return View::make('admin.volume.volume', with(['volume_list' => $volume_list,
         'volume_search' => $volume_search,
          'journal_search' => $journal_search,
           'year_search' => $year_search,
            'param' => $param,
             'editPermission' => $editPermission, 
             'deletePermission' => $deletePermission]));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function add()
    {

        $journal = Journal::GetJournalTitle();

        return View::make('admin.volume.addvolume')->with('journal', $journal);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {

        $journal     = Journal::GetJournalTitle();
        $year_search = Journal::GetYear();

        return View::make('admin.volume.addvolume', with(['journal' => $journal, 'year_search' => $year_search]));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $validator = Validator::make($request->all(), [
            'volume_name' => 'required',
            'volume_name' => 'numeric',
            'journal_id'  => 'required',
            'year_id'     => 'required',
        ]);

        $validator->after(function ($validator) use ($request) {

            $p['journal_id']  = $journal_id  = $request->get("journal_id");
            $p['volume_name'] = $volume_name = $request->get("volume_name");

            $exist_volume = Volume::GetVolumeById($p);

            if (!empty($exist_volume[0])) {
                $validator->errors()->add('volume_name', 'Volume name already exist');
            }

        });

        // process the login
        if ($validator->fails()) {
            return back()->withInput()->withErrors($validator);
        } else {
            $this->insertVolume($request);            return Redirect::to('admin/volumes');
        }

    }

    public function update(Request $request, $volume_id)
    {
        $input = $request->all();

        $validator = Validator::make($request->all(), [
            'volume_name' => 'required',
            'volume_name' => 'numeric',
            'journal_id'  => 'required',
            'year_id'     => 'required',
        ]);

        $validator->after(function ($validator) use ($volume_id,$request) {

            $p['journal_id']  = $journal_id  = $request->get("journal_id");
            $p['volume_name'] = $volume_name = $request->get("volume_name");
            $p['volume_id']   = $volume_id;

            $exist_volume = Volume::CheckVolumeExist($p);

            if (!empty($exist_volume)) {
                $validator->errors()->add('volume_name', 'Volume name already exist');
            }

        });

        // process the login
        if ($validator->fails()) {
            return back()->withInput()->withErrors($validator);
        } else {
            $this->updateVolume($request, $volume_id);            return Redirect::to('admin/volumes');
        }

    }

    public function destroy(Request $request, $volume_id)
    {

		$issue = Issue::where('volume_id', $volume_id)->first();
		
		if (empty($issue)) 
		{
			
			$volume = Volume::where('volume_id', $volume_id)->first();
			$delete_volume['volume_id']             =$volume->volume_id;
			$delete_volume['nid']                	=$volume->nid;
			$delete_volume['journal_id']         	=$volume->journal_id;
			$delete_volume['year_id']            	=$volume->year_id;
			$delete_volume['volume_name']       	=$volume->volume_name;
			$delete_volume['total_no_of_issues']    =$volume->total_no_of_issues;
			$delete_volume['introduction']       	=$volume->introduction;
			$delete_volume['publication_date']      =$volume->publication_date;
			$delete_volume['expected_date']         =$volume->expected_date;
			$delete_volume['url']        			=$volume->url;
			$delete_volume['is_uploaded']        	=$volume->is_uploaded;
			$delete_volume['created']       	 	=$volume->created;
			$delete_volume['created_by']        	=$volume->created_by;
			$delete_volume['updated_by']        	=$volume->updated_by;
		
			
			$node = Node::where('nid', $volume->nid)->first();
			$delete_node['nid'] =   $node->nid;
			$delete_node['type'] =   $node->type;
			$delete_node['language'] =   $node->language;
			$delete_node['title'] =   $node->title;
			$delete_node['uid'] =   $node->uid;
			$delete_node['status'] =   $node->status;
			$delete_node['created'] =   $node->created;
			$delete_node['changed'] =   $node->changed;
			$delete_node['comment'] =   $node->comment;
			$delete_node['promote'] =   $node->promote;
			$delete_node['moderate'] =   $node->moderate;
			$delete_node['sticky'] =   $node->sticky;
			$delete_node['tnid'] =   $node->tnid;
			$delete_node['translate'] =   $node->translate;
			
			
			$node_meta = Meta::where('nid', $volume->nid)->first();
			$delete_node_meta['node_meta_id'] = $node_meta->node_meta_id;
			$delete_node_meta['nid'] = $node_meta->nid;
			$delete_node_meta['title'] = $node_meta->title;
			$delete_node_meta['abstract'] = $node_meta->abstract;
			$delete_node_meta['canonical_url'] = $node_meta->canonical_url;
			$delete_node_meta['copyright'] = $node_meta->copyright;
			$delete_node_meta['description'] = $node_meta->description;
			$delete_node_meta['keywords'] = $node_meta->keywords;
		
        try {// try transaction start here for data integrity

            DB::beginTransaction();

			Volume::where('volume_id', $volume_id)->delete();
			Node::where('nid', $volume->nid)->delete();
			Meta::where('nid', $volume->nid)->delete();
			
			//-----------------------------Delete into log table-----------------------------------

			$log_node['node']      = $delete_node;
			$log_volume['volume']  = $delete_volume;
			$log_meta['node_meta'] = $delete_node_meta;

			$log     = array_merge($log_node, $log_volume, $log_meta);
			$user                             = Auth::user();
			$add_log = array(
				'content_id'      => $volume['volume_id'],
				'content_type_id' => config('constants.log_content_types.Volume'),
				'action'          => config('constants.log_action_types.delete'),
				'log_data'        => json_encode($log),
				'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::to('admin/volumes');
            }

		}
		else
		{
			return back()->with(['delete_msg' => 'Issue already exist in this volume']);
			
		}	
		
        return redirect()->back()->with('success', 'Volume delete successfully.');    
    }

    public function edit($id)
    {
        $p['volume_id'] = $id;
        $volume         = Volume::GetVolumeById($p);
        $journal        = Journal::GetJournalTitle();
        $year_search    = Journal::GetYear();
        $volume         = $volume[0];

        $selected_meta = Meta::NodeMeta($volume->nid);

        return View::make('admin.volume.addvolume', with(['volume' => $volume,
         'journal' => $journal,
          'year_search' => $year_search,
           'selected_meta' => $selected_meta]));
    }

    public function insertVolume($request)
    {
        
    try {// try transaction start here for data integrity

        DB::beginTransaction();
        $journal_id = $request->get('journal_id');

        //-------------------Insert into Node table---------------
        $add_node['type']    = 'volume';
        $add_node['title']   = $request->get('volume_name');
        $add_node['created'] = time();
        $add_node['nid']     = Node::insertGetId($add_node);

        //-------------------Insert into Volume table---------------
        $user                             = Auth::user();
        $add_volume['nid']                = $add_node['nid'];
        $add_volume['journal_id']         = $request->get('journal_id');
        $add_volume['year_id']            = $request->get('year_id');
        $add_volume['volume_name']        = $request->get('volume_name');
        $add_volume['total_no_of_issues'] = $request->get('total_no_of_issues');
        $add_volume['created']            = time();
        $add_volume['created_by']         = $user->id;
        $add_volume['updated_by']         = $user->id;
        $add_volume['volume_id']          = Volume::insertGetId($add_volume);

        //-------------------Insert into Meta table---------------
        $add_node_meta['nid']           = $add_node['nid'];
        $add_node_meta['abstract']      = $request->get('meta_abstract');
        $add_node_meta['canonical_url'] = $request->get('meta_canonical_url');
        $add_node_meta['copyright']     = $request->get('meta_copyright');
        $add_node_meta['description']   = $request->get('meta_description');
        $add_node_meta['keywords']      = $request->get('meta_keywords');
        $add_node_meta['node_meta_id']  = Meta::insertGetId($add_node_meta);

        //-----------------------------Insert into log table-----------------------------------

        $log_node['node']      = $add_node;
        $log_volume['volume']  = $add_volume;
        $log_meta['node_meta'] = $add_node_meta;

        $log     = array_merge($log_node, $log_volume, $log_meta);
        $add_log = array(
            'content_id'      => $add_volume['volume_id'],
            'content_type_id' => config('constants.log_content_types.Volume'),
            'action'          => config('constants.log_action_types.insert'),
            'log_data'        => json_encode($log),
            '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::to('admin/volumes');
        }

    }

    public function updateVolume($request, $volume_id)
    {
    try {// try transaction start here for data integrity

        DB::beginTransaction();

        $volume = Volume::where('volume_id', $volume_id)->get();
        $volume = $volume[0];

        //-------------------Update into Volume table---------------
        $user                                = Auth::user();
        $update_volume['journal_id']         = $request->get('journal_id');
        $update_volume['year_id']            = $request->get('year_id');
        $update_volume['volume_name']        = $request->get('volume_name');
        $update_volume['total_no_of_issues'] = $request->get('total_no_of_issues');
        $update_volume['updated_by']         = $user->id;
        Volume::where('volume_id', $volume_id)->update($update_volume);
        $update_volume['volume_id'] = $volume->volume_id;

        //-------------------Update into Meta table---------------

        Meta::where('nid', $volume->nid)->delete();
        $add_node_meta['nid']           = $volume->nid;
        $add_node_meta['abstract']      = $request->get('meta_abstract');
        $add_node_meta['canonical_url'] = $request->get('meta_canonical_url');
        $add_node_meta['copyright']     = $request->get('meta_copyright');
        $add_node_meta['description']   = $request->get('meta_description');
        $add_node_meta['keywords']      = $request->get('meta_keywords');
        $add_node_meta['node_meta_id']  = Meta::insertGetId($add_node_meta);

        //-----------------------------Insert into log table-----------------------------------

        $log_volume['volume'] = $update_volume;
        $log_meta['meta']     = $add_node_meta;

        $log     = array_merge($log_volume, $log_meta);
        $add_log = array(
            'content_id'      => $volume_id,
            'content_type_id' => config('constants.log_content_types.Volume'),
            'action'          => config('constants.log_action_types.update'),
            'log_data'        => json_encode($log),
            '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::to('admin/volumes');
        }

    }

}
