<?php

namespace App\Http\Controllers;

use App\Models\Meta;
use App\Models\Node;
use App\Models\Log;
use App\Models\PharmacyCollection;
use App\Models\Ebook;
use App\Models\EbookVolume;
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 PharmacyCollectionController extends BenthamController
{

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

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

        $pharmacy_collection_list = PharmacyCollection::getAllPharmacyCollection($search);

        return view('admin/pharmacy_collection/pharmacy_collection_list', ['pharmacy_collection_list' => $pharmacy_collection_list, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission, 'createPermission' => $createPermission]);
        //return $subject_data;
    } 
    //Get All Subject
/*    public function GetPharmacyCollectionList()
    {
        $subject_list = Subject::GetSubject();
        return view('admin/subject', ['subject_list' => $subject_list]);
        //return $subject_data;
    }
*/  
    public function create(Request $request)
    {
        $journal = Journal::GetJournalTitle();
        $ebook_volume = EbookVolume::GetAllEbookVolumeList();
        return view('admin.pharmacy_collection.add_pharmacy_collection')->with(['journal' => $journal, 'ebook_volume' => $ebook_volume]);
    }    
    //Add Subject
    public function store(Request $request)
    {  
        //dd($request);
        $log_ebook_pharmacy = $log_ebook_pharmacy = array();       
        
        $validator = Validator::make($request->all(), [
            'title'  => 'required',
            'pc_type'  => 'required',
            'journal_id' => 'required_if:pc_type,j',
            'ebook_volume_id' => 'required_if:pc_type,e,',
        ],
        [
            'journal_id.required_if' => 'Plz select pharmacy journal',
            'ebook_volume_id.required_if' => 'Plz select pharmacy ebooks',
        ]);

        if ($validator->fails()) {
            return redirect('admin/pharmacy_collection/create')
                ->withErrors($validator)
                ->withInput();
        } else {

            try {
            // try transaction start here for data integrity

                DB::beginTransaction();

                $user     = Auth::user();

                $title            = $request->input('title');
                $description      = $request->input('description');
                $pc_type          = $request->input('pc_type');
                $meta_abstract    = $request->input('meta_abstract');
                $meta_canonical   = $request->input('meta_canonical_url');
                $meta_copyright   = $request->input('meta_copyright');
                $meta_description = $request->input('meta_description');
                $meta_keywords    = $request->input('meta_keywords');
                $time_stamp       = time();
                //---------Add to node table-----------//        
                $add_node = array(
                            'type'    => 'pharmacy_collection',
                            'title'   => $request->input('title'),
                            'uid'     => $user->id,
                            'status'  => 1,
                            'created' => time(),
                            'changed' => time(),
                        );
                $node_id = Node::Add($add_node);

                //---------Add to subject table-----------//
                $add_pharmacy_collection = array('nid' => $node_id,
                    'title'                        => $title,
                    'description'                  => $description,
                    'pc_type'                      => $pc_type,
                    'created_by'                   => $user->id,
                    'created_on'                   => time(),
                    'last_modify_by'               => $user->id,
                    'last_modify_on'               => time()
                );

                $pharmacy_collection_id = PharmacyCollection::Add($add_pharmacy_collection);

                //---------Add to node meta table-----------//
                $add_node_meta = array('nid' => $node_id,
                    'title'                      => $title,
                    'abstract'                   => $meta_abstract,
                    'canonical_url'              => $meta_canonical,
                    'copyright'                  => $meta_copyright,
                    'description'                => $meta_description,
                    'keywords'                   => $meta_keywords);

                Meta::AddNodeMeta($add_node_meta);
                
                $log_meta['meta'] = $add_node_meta;

                //---------------------Inert into journal pharmacy table--------

                if (isset($request->journal_id) && count($request->journal_id)) {

                    $journal_id = $request->journal_id;

                    if (!empty($journal_id)) {
                        for ($b = 0; $b < count($journal_id); $b++) {
                            $add_journal_pharmacy[] = array(
                                'pc_id'      => $pharmacy_collection_id,
                                'journal_id' => $journal_id[$b]);

                            $log_journal_pharmacy['journal_pharmacy'][$b] = $add_journal_pharmacy;
                        }
                        
                        PharmacyCollection::AddPharmacyCollectionJournal($add_journal_pharmacy);
                    }
                }
                //---------------------Inert into ebook pharmacy table--------
                if (isset($request->ebook_volume_id) && count($request->ebook_volume_id)) {
                   
                    $ebook_volume_id = $request->ebook_volume_id;
                   
                    if (!empty($ebook_volume_id)) {
                        for ($b = 0; $b < count($ebook_volume_id); $b++) {
                            $add_ebook_pharmacy[] = array(
                                'pc_id'      => $pharmacy_collection_id,
                                'ebook_volume_id' => $ebook_volume_id[$b]);

                            $log_ebook_pharmacy['ebook_pharmacy'][$b] = $add_ebook_pharmacy;
                        }
                        
                        PharmacyCollection::AddPharmacyCollectionEbook($add_ebook_pharmacy);
                    }
                }


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

                $log     = array_merge($add_node, $add_pharmacy_collection, $log_meta, $log_ebook_pharmacy, $log_ebook_pharmacy);
                $add_log = array(
                    'content_id'      => $pharmacy_collection_id,
                    'content_type_id' => config('constants.log_content_types.Pharmacy_Collection'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($log),
                    'created_dated'   => time(),
                    'created_by'      => Auth::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/pharmacy_collection');
            }

            Session::flash('success', 'Pharmacy Collection Has Been Added Successfully!');
            return Redirect::to('admin/pharmacy_collection');
        }
    }

    public function edit($id)
    {
        $selected_journal = $selected_book = array();
        $user = Auth::user()->id;

        $selected_pharmacy_collection = PharmacyCollection::GetPharmacyCollectionById($id);        
        $selected_meta = Meta::NodeMeta($selected_pharmacy_collection->nid);

        $pharmacy_journal = PharmacyCollection::getAllJournalsByPharmacyCollectionId($id);
        
        $pharmacy_ebook = PharmacyCollection::getAllEbooksByPharmacyCollectionId($id);

        foreach ($pharmacy_journal as $key => $value) {
            $selected_journal[] = $value->journal_id;
        }

        foreach ($pharmacy_ebook as $key => $value) {
            $selected_book[] = $value->ebook_volume_id;
        }

        $journal = Journal::GetJournalTitle();
        $ebook_volume = EbookVolume::GetAllEbookVolumeList();

        return view('admin.pharmacy_collection.add_pharmacy_collection')->with(['user' => $user, 'selected_pharmacy_collection' => $selected_pharmacy_collection, 'selected_meta' => $selected_meta, 'selected_journal' => $selected_journal, 'selected_book' => $selected_book,'journal' => $journal, 'ebook_volume' => $ebook_volume]);
    }

     public function update(Request $request, $id)
    {   
        $log_journal_pharmacy = $log_ebook_pharmacy = array();       
        $pharmacy_collection      = array();       
        $log_meta            = array();

        //-------------- Journal Validation------------------
        $validator = Validator::make($request->all(), [            
            'title'           => 'required'            
        ]);

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

            try {
            // try transaction start here for data integrity

                DB::beginTransaction();

                $pc_id  = $request->input('pc_id');
                $nid    = $request->input('nid');
                $user   = Auth::user();

                $pharmacy_collection = array(
                    'pc_id'                   => $pc_id,
                    'nid'                     => $nid,                    
                    'title'                   => $request->input('title'),
                    'description'             => $request->input('description'),
                    'pc_type'                 => $request->input('pc_type'), 
                    'last_modify_by'          => $user->id,
                    'last_modify_on'          => time()
                );

                PharmacyCollection::PharmacyCollectionUpdate($pharmacy_collection);

               
                //-------------------Inert into Node Meta table---------------
                Meta::DeleteMeta($nid);

                $add_node_meta = array(
                    'nid'           => $nid,
                    'title'         => $request->input('title'),
                    'abstract'      => $request->input('meta_abstract'),
                    'canonical_url' => $request->input('meta_canonical_url'),
                    'copyright'     => $request->input('meta_copyright'),
                    'description'   => $request->input('meta_description'),
                    'keywords'      => $request->input('meta_keywords'),
                );

                $node_meta = Meta::AddNodeMeta($add_node_meta);

                //---------------------Inert into journal pharmacy table--------
                PharmacyCollection::DeletePharmacyCollectionJournal($id);
                
                if (isset($request->journal_id) && count($request->journal_id)) {

                    $journal_id = $request->journal_id;

                    if (!empty($journal_id)) {
                        for ($b = 0; $b < count($journal_id); $b++) {
                            $add_journal_pharmacy[] = array(
                                'pc_id'      => $id,
                                'journal_id' => $journal_id[$b]);

                            $log_journal_pharmacy['journal_pharmacy'][$b] = $add_journal_pharmacy;
                        }
                        
                        PharmacyCollection::AddPharmacyCollectionJournal($add_journal_pharmacy);
                    }
                }
                //---------------------Inert into ebook pharmacy table--------
                PharmacyCollection::DeletePharmacyCollectionEbook($id);

                if (isset($request->ebook_volume_id) && count($request->ebook_volume_id)) {
                   
                    $ebook_volume_id = $request->ebook_volume_id;
                   
                    if (!empty($ebook_volume_id)) {
                        for ($b = 0; $b < count($ebook_volume_id); $b++) {
                            $add_ebook_pharmacy[] = array(
                                'pc_id'      => $id,
                                'ebook_volume_id' => $ebook_volume_id[$b]);

                            $log_ebook_pharmacy['ebook_pharmacy'][$b] = $add_ebook_pharmacy;
                        }
                        
                        PharmacyCollection::AddPharmacyCollectionEbook($add_ebook_pharmacy);
                    }
                }


                $log_meta['meta'] = $add_node_meta;

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

                $log     = array_merge($pharmacy_collection, $log_meta, $log_ebook_pharmacy, $log_journal_pharmacy);
                $add_log = array(
                    'content_id'      => $pc_id,
                    'content_type_id' => config('constants.log_content_types.Pharmacy_Collection'),
                    'action'          => config('constants.log_action_types.update'),
                    'log_data'        => json_encode($log),
                    'created_dated'   => time(),
                    'created_by'      => Auth::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/pharmacy_collection');
            }

            Session::flash('success', 'Pharmacy Collection Has Been Added Successfully!');
            return Redirect::to('admin/pharmacy_collection');
        }
    }


    public function destroy($id)
    {   
        $user     = Auth::user();
        $pharmacy_collection = array(
            'pc_id'                   => $id,
            'pc_status'               => 0,
            'last_modify_by'          => $user->id,
            'last_modify_on'          => time()
        );

        PharmacyCollection::PharmacyCollectionUpdate($pharmacy_collection);
        
        return redirect()->route('pharmacy_collection.index')->with('success', 'Pharmacy Collection Deleted Successfully.');
    }

    public function browse_by_pharmacy_collection(){

        $pharmacy_collection_list = PharmacyCollection::PharmacyCollections('j');

        return view('pharmacy_collection', ['pharmacy_collection_list' => $pharmacy_collection_list,'pc_type' => 'j']);
    }

    public function browse_by_ebook_pharmacy_collection(){

        $pharmacy_collection_list = PharmacyCollection::PharmacyCollections('e');
        
        return view('pharmacy_collection', ['pharmacy_collection_list' => $pharmacy_collection_list,'pc_type' => 'e']);
    }

    public function DisplayPharmacyCollection(Request $request){

        $pharmacy_collection_title = array();
        
        $pharmacy_collection_title = PharmacyCollection::GetPharmacyCollectionTitleBylID($request->pc_id);

        $journal = PharmacyCollection::getAllJournalsByPharmacyCollectionId($request->pc_id);

        return view('pharmacy_collection_journal', with(['pharmacy_collection_title' => $pharmacy_collection_title,
            'journal' => $journal]));
    }
    public function DisplayEbookPharmacyCollection(Request $request){

        $pharmacy_collection_title = PharmacyCollection::GetPharmacyCollectionTitleBylID($request->pc_id);

        $ebook_volume = array();

        $letter = '';
        
        $param  = array();

        $param['pc_id'] = $request->pc_id;

        list($ebook_volume,$sample_types)    = EbookVolume::SearchEbookVolumeList($letter, $param);

        $year = Journal::GetYear();

        $searchFormRoute = 'bybook';

        return view('ebook.ebook_volume_list', with(['ebook_volume' => $ebook_volume,
          'year' => $year,
           'searchFormRoute' => $searchFormRoute,
           'sample_types' => $sample_types,
           'pharmacy_collection_title' => $pharmacy_collection_title
       ]));
    }

}
