<?php
namespace App\Http\Controllers;
use Yajra\Datatables\Datatables as Datatables;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Facades\Excel;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use App\Helper\MailHelper as MailHelper;
use Notification;
use Auth;
use App\Models\User;
use App\Models\Settings\Organisation;
use App\Models\Settings\Department;
use App\Models\Settings\Section;
use App\Models\Settings\MaterialType;
use App\Models\Settings\MaterialSubType;
use App\Models\Settings\Topic;
use App\Models\Settings\ContentType;
use App\Models\Settings\MimeType;
use App\Models\Settings\Roles;
use App\Models\Settings\Permissions;
use App\Models\Settings\RolePermission;
use App\Models\Settings\UserRoles;
use App\Models\Content\Content;
use App\Models\Content\ContentDocument;
use App\Models\Content\ContentAssignment;
use App\Models\Content\RejectClarify;
use App\Models\Content\Marks;
use App\Models\Notification\Notification_Bell;
use App\Models\Notification\Notifications;

use Request as req;

class ContentController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function get_contenttype($organisation_id)
    {
        $contenttypes=ContentType::where('organisation_id',$organisation_id)->get();
        return $contenttypes->pluck('content_type_name', 'id');
    }
    public function get_content($material_type_id)
    {
        $contents=ContentAssignment::where('material_type_id',$material_type_id)->with('contentname')->get();
        return $contents->pluck('contentname.content_subject', 'id');
    }
    /////create content /////
    public function create_content()
    {
        $organisations = Organisation::all();
        $contenttypes=ContentType::all();
        return view('Content/create_content', compact('organisations','contenttypes'));
    }
    public function create_content_post(Request $request)
    {
        $messsages = array(
            'content_type_id.required'=>'Select content type',
            'content_subject.required'=>'Enter content subject',
            );
        $rules = array(
            'content_type_id'=>'required',
            'content_subject'=>'required|max:250',
            );
        Validator::make($request->all(), $rules,$messsages)->validate();
        $insert_id="";
        $content_type_id =$request->content_type_id;
        $content_subject = $request->content_subject;
        $description = $request->description;
        $id = Auth::user()->id;
        $content_count = Content::where('content_subject',$content_subject)->where('content_type_id',$content_type_id)->count();
        if($content_count==0)
        {
            $insert_id = Content::create([
                'content_type_id' => $content_type_id,
                'content_subject' => $content_subject,
                'description' => $description,
                'created_by' => $id,
                'status' => 1,
            ]);
            $content_id = $insert_id->id;
            $doc_count = $request->doc_count;
            for($i=1;$i<=$doc_count;$i++)
            {
                $document_name="document_name".$i;
                $document_path ="document_path".$i;
                if ($request->hasFile($document_path)) 
                {
                    $fileobj=$request->file($document_path)->getClientOriginalName();

                    $destpath="uploads/content/document";

                    $custom_file_name =$content_id.'-'.$fileobj;

                    $path = $request->file($document_path)->storeAs($destpath,$custom_file_name);

                    $file_extension = $request->file($document_path)->getClientOriginalExtension();
                    if($file_extension)
                    {
                        $mime_type_arr = MimeType::where('mime_type',$file_extension)->first();
                        if(isset($mime_type_arr))
                        {
                            $mime_type_id = $mime_type_arr->id;
                        }
                    }
                    $insert_doc_path_id = ContentDocument::create([
                        'content_id' => $content_id,
                        'document_name' => $request->$document_name,
                        'document_path' => $path,
                        'mime_type_id' => $mime_type_id,
                        'updated_by' => $id,
                    ]);
                }
            }
        }
        if($insert_id)
            notify()->success('Content has been added');
        else
            smilify('Error', '');

        return redirect()->back();
    }
    public function get_content_details(Request $request)
    {
        $columns = array(
            0=> 'id',
            1=>'content_type_name',
            2=>'content_subject',
            3=>'description',
            4=> 'action',
        );
        $totalData = Content::count();
        $totalFiltered = $totalData; 
        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        if(empty($request->input('search.value')))
        {       
            $posts = Content::with('content_type')
                         ->offset($start)
                         ->limit($limit)
                         ->orderBy('id','desc')
                         ->get();
        }
        else 
        {
            $search = $request->input('search.value'); 
            $posts =  Content::with('content_type')->where('content_subject', 'LIKE',"%{$search}%")
                            ->orWhere('description', 'LIKE',"%{$search}%")
                            ->offset($start)
                            ->limit($limit)
                            ->orderBy($order,$dir)
                            ->get();
            $totalFiltered = Content::with('content_type')->where('content_subject', 'LIKE',"%{$search}%")
                            ->orWhere('description', 'LIKE',"%{$search}%")
                            ->count();
        }
        $data = array();
        if(!empty($posts))
        {
            foreach ($posts as $post)
            {   
                if(isset($post->content_type_id))
                    $content_type_name = $post->content_type->content_type_name;
                $nestedData['DT_RowIndex'] = $post->id;
                $nestedData['content_type_name'] = $content_type_name;
                $nestedData['content_subject'] = $post->content_subject;
                $nestedData['description'] = $post->description;
                $nestedData['action'] = '<a href="'.url('show_content').'/'.$post->id.'" title="Update Content"><span style="color:blue;"><i class="fa fa-edit"></i></span></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#"  title="Delete Contents" onClick="confirmDeleteContent('.$post->id.');"><span style="color:red;"><i class="fa fa-btn fa-minus-circle"></i></span></a>';
                $data[] = $nestedData;
            }
        }
        $json_data = array(
                    "draw"            => intval($request->input('draw')),  
                    "recordsTotal"    => intval($totalData),  
                    "recordsFiltered" => intval($totalFiltered), 
                    "data"            => $data   
                    );
        echo json_encode($json_data); 
    }
    public function show_content($id)
    {
        $contents = Content::where('id',$id)->with('content_type','content_document')->first();
        return view('Content/show_content', compact('contents'));
    }
    public function show_content_post(Request $request)
    {
        $insert_id="";
        $content_subject = $request->content_subject;
        $description = $request->description;
        $content_id = $request->content_id;
        $id = Auth::user()->id;
        $upd_flg = 0;
        $contents = Content::where('id',$content_id)->first();
        if(isset($contents))
        {
            $contents->content_subject=$content_subject;
            $contents->description=$description;
            $contents->save();
            $mimetype_id = "";
            $document_deletes = ContentDocument::where('content_id',$content_id)->delete();
            $doc_count = $request->doc_count;
            for($i=1;$i<=$doc_count;$i++)
            {
                $document_name="document_name".$i;
                $document_path ="document_path".$i;
                $mime_type_id = "mime_type_id".$i;
                if ($request->hasFile($document_path)) 
                {
                    $fileobj=$request->file($document_path)->getClientOriginalName();

                    $destpath="uploads/content/document";

                    $custom_file_name =$content_id.'-'.$fileobj;

                    $path = $request->file($document_path)->storeAs($destpath,$custom_file_name);

                    $file_extension = $request->file($document_path)->getClientOriginalExtension();
                    if($file_extension)
                    {
                        $mime_type_arr = MimeType::where('mime_type',$file_extension)->first();
                        if(isset($mime_type_arr))
                        {
                            $mimetype_id = $mime_type_arr->id;
                        }
                    }
                    $insert_doc_path_id = ContentDocument::create([
                        'content_id' => $content_id,
                        'document_name' => $request->$document_name,
                        'document_path' => $path,
                        'mime_type_id' => $mimetype_id,
                        'updated_by' => $id,
                    ]);
                }
                else
                {
                   $insert_doc_path_id = ContentDocument::create([
                        'content_id' => $content_id,
                        'document_name' => $request->$document_name,
                        'document_path' => $request->$document_path,
                        'mime_type_id' => $request->$mime_type_id,
                        'updated_by' => $id,
                    ]); 
                }
            }

            $upd_flg = 1;
        }
        if($upd_flg)
            notify()->success('Content has been updated');
        else
            smilify('Error', '');

        return redirect('create_content');
    }
    public function delete_content(Request $request)
    {
        $id = $request->id;
        $topic_content_count = ContentAssignment::where('content_id',$id)->count();
        if($topic_content_count==0)
        {
            $content_document_delete = ContentDocument::where('content_id',$id)->delete();
            $content_delete=Content::where('id',$id)->delete();
            return 1;
            
        }
        else
        {
            return 0;
        }
    }

    /////assign content /////
    public function assign_content()
    {
        $organisation_id = Auth::user()->organisation_id;
        $contents = Content::with('content_assignment')->get();
        //dd($contents);
        return view('Content/assign_content', compact('contents'));
    }
    public function assign_content_show(Request $request)
    {
        $content_assignments = "";
        $organisations = Organisation::all();
        $content_id = $request->content_id;
        $contents = Content::where('id',$content_id)->with('content_type')->first();
        $content_assignments = ContentAssignment::where('content_id',$content_id)->with('organisation','department','section','materialtype','materialsubtype','topic')->get();
        return view('Content/assign_content_show', compact('contents','organisations','content_assignments'));
    }
    public function assign_content_post(Request $request)
    {
        
        $insert_id="";
        $organisation_id = $request->organisation_id;
        $department_id = $request->department_id;
        $section_id = $request->section_id;
        $content_id =$request->content_id;
        $material_type_id = $request->material_type_id;
        $material_subtype_id = $request->material_subtype_id;
        $topic_id = $request->topic_id;
        $id = Auth::user()->id;
        
        $insert_content_assignment_id = ContentAssignment::create([
            'organisation_id' => $organisation_id,
            'department_id' => $department_id,
            'section_id' => $section_id,
            'content_id' => $content_id,
            'material_type_id' => $material_type_id,
            'material_subtype_id' => $material_subtype_id,
            'topic_id' => $topic_id,
        ]);
        
        if($insert_content_assignment_id)
            notify()->success('Content has been Assigned');
        else
            smilify('Error', '');

        return redirect('assign_content');
    }
    public function view_content_assignments($content_id)
    {
        $contents = Content::where('id',$content_id)->with('content_type')->first();
        $content_assignments = ContentAssignment::where('content_id',$content_id)->with('organisation','department','section','materialtype','materialsubtype','topic','contentname')->get();
        return view('Content/view_content_assignments', compact('content_assignments','contents'));
    }

    /////ranking /////
    public function ranking()
    {
        $organisations = Organisation::all();
        return view('Content/ranking', compact('organisations'));
    }
    public function ranking_post(Request $request)
    {
        $messsages = array(
            'weighted_mark.required'=>'Please enter weighted mark name',
            );
        $rules = array(
            'weighted_mark'=>'required',
            );
        Validator::make($request->all(), $rules,$messsages)->validate();
        $insert_id="";
        $organisation_id = $request->organisation_id;
        $material_type_id = $request->material_type_id;
        $weighted_average_mark=$request->weighted_mark;
        $content_id = $request->content_id;
        $id = Auth::user()->id;
        $ranking_count = Marks::where('material_type_id',$material_type_id)->where('organisation_id',$organisation_id)->count();
        if($ranking_count==0)
        {
                $insert_id = Marks::create([
                    'organisation_id' => $organisation_id,
                    'material_type_id' => $material_type_id,
                    'content_id' => $content_id,
                    'weighted_average_mark' => $weighted_average_mark,
                ]);
        }
        if($insert_id)
            notify()->success('Ranking has been added');
        else
            smilify('Error', '');

        return redirect()->back();
    }

}
