<?php

namespace App\Http\Controllers;

use App\Tutorial;
use App\Batch;
use App\TutorialType;
use App\Subject;
use App\User;
use App\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use DataTables;

class TutorialController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['list','allTutorials','tutorialDetails','totalCount','allFacultyTutorials','store']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function index()
    // {
    //     //
    // }

    public function index(Request $request, $id)
    {
        $data = Batch::where('batches.id', $id)
            ->leftJoin('courses', 'batches.courseid', '=', 'courses.id')
            ->select('batches.id', 'courses.name', 'currentsem', 'batch')->first();
        $coursename = $data->name;
        $batch = $data->batch;
        return view('tutorial.index', compact('id', 'coursename', 'batch'));
    }


    public function showtutorials($id, $status)
    {
       if ($status == "active") {
            $data = Tutorial::latest()->where('batchid', $id)->get();
        } else {
            $data = Tutorial::onlyTrashed()->where('batchid', $id)->get();
        }

        return Datatables::of($data)
            ->addIndexColumn()
            ->addColumn('edit', function ($row) {

                $btn = '<a href="/tutorial/' . $row->id . '/edit" class="edit btn btn-primary btn-sm">Edit</a>';
                if ($row->deleted_at != null) {
                    $btn = "";
                }
                return $btn;
            })
            ->addColumn('delete', function ($row) {
                if (is_null($row->deleted_at)) {
                    $btn = '<a href="javascript:void(0)" data-id="' . $row->id . '" class="deleteData btn btn-danger btn-sm">Delete</a>';
                } else {
                    $btn = '<a href="javascript:void(0)" data-id="' . $row->id . '" class="restoreData btn btn-success btn-sm">Restore</a>';
                }
                return $btn;
            })
            ->rawColumns(['edit', 'delete'])
            ->make(true);
    }

   /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($facultyid, Request $request)
    {
        $batchid = $request->batchid;
        $semester = $request->semester;
        $subjectid = $request->subjectid;

        $data = Batch::where('batches.id', $batchid)
            ->leftJoin('courses', 'batches.courseid', '=', 'courses.id')
            ->select('batches.id', 'courses.name', 'batch')->first();

        $coursename = $data->name;
        $batch = $data->batch;

        $subjects = Subject::where('id', $subjectid)
            ->select('name')->first();
        $subjectname = $subjects->name;

        $tutorialTypes = TutorialType::all(['id', 'name']);

        return view('tutorial.create', compact('facultyid', 'batchid', 'subjectid', 'coursename', 'subjectname', 'batch', 'semester', 'tutorialTypes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        
        error_log("Faculty " . $request->facultyid);
        $tutorial = new Tutorial($request->input());

        if ($file = $request->hasFile('attachment')) {

            $file = $request->file('attachment');

            $fileName = $file->getClientOriginalName();
            $destinationPath = public_path() . '/uploads/';
            $file->move($destinationPath, $fileName);
            $tutorial->attachment = $fileName;
        }
        $tutorial->save();

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Tutorial  $tutorial
     * @return \Illuminate\Http\Response
     */
    public function show(Tutorial $tutorial)
    {
        return $tutorial;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Tutorial  $tutorial
     * @return \Illuminate\Http\Response
     */
    public function edit(Tutorial $tutorial)
    {
        $batchid = $tutorial->batchid;
        $semester = $tutorial->semester;
        $subjectid = $tutorial->subjectid;
        $facultyid = $tutorial->facultyid;

        $data = Batch::where('batches.id', $batchid)
            ->leftJoin('courses', 'batches.courseid', '=', 'courses.id')
            ->select('batches.id', 'courses.name', 'batch')->first();

        $coursename = $data->name;
        $batch = $data->batch;

        $subjects = Subject::where('id', $subjectid)
            ->select('name')->first();
        $subjectname = $subjects->name;

        $tutorialTypes = TutorialType::all(['id', 'name']);

        $tutorials = Tutorial::select('id','title','details','videolink','attachment')->first();

        return view('tutorial.edit', compact('facultyid', 'batchid', 'subjectid', 'coursename', 'subjectname', 'batch', 'semester', 'tutorialTypes', 'tutorials'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Tutorial  $tutorial
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Tutorial $tutorial)
    {
        // if ($tutorial->fill($request->all())->save()) {
        //     return true;
        // }

        $tutorialx = $tutorial->fill($request->input());

        if ($file = $request->hasFile('attachment')) {

            $file = $request->file('attachment');

            $fileName = $file->getClientOriginalName();
            $destinationPath = public_path() . '/uploads/';
            $file->move($destinationPath, $fileName);
            $tutorialx->attachment = $fileName;
        }
        $tutorialx->save();
    }

    /**
     * restore the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Tutorial  $tutorial
     * @return \Illuminate\Http\Response
     */
    public function restore(Request $request)
    {
        Tutorial::withTrashed()
            ->where('id', $request->id)
            ->restore();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Tutorial  $tutorial
     * @return \Illuminate\Http\Response
     */
    public function destroy(Tutorial $tutorial)
    {
        $tutorial->deleted_by = Auth::id();
        $tutorial->save();
        if ($tutorial->delete()) {
            return true;
        }
    }

    public function list()
    {
        $data=Tutorial::latest()->get();

        return compact('data');
    }


    public function downloadFile($id)
    {
        $data = Tutorial::where('id', $id)->first();
        $filename = $data->attachment;
        error_log("File " . $filename);
        //PDF file is stored under project/public/download/info.pdf
        $file = public_path() . '/uploads/' . $filename;

        $headers = array(
            'Content-Type: application/octet-stream',
        );

        return response()->download($file);
    }

    public function allTutorials($batchid)
    {
        $data = Tutorial::join('subjects','subjects.id','=','tutorials.subjectid')
        ->join('faculties','faculties.id','=','tutorials.facultyid')
        ->join('tutorial_types','tutorial_types.id','=','tutorials.tutorialtypeid')
        ->where('tutorials.batchid','=',$batchid)
        ->select('tutorials.id as tutorialid','title','subjects.name as subjectname','faculties.name as facultyname','tutorials.created_at as created_at','tutorial_types.name as tutorialtype')->get();
        
        return compact('data');
   
    }

    public function allFacultyTutorials($facultyid)
    {
        $data = Tutorial::join('subjects','subjects.id','=','tutorials.subjectid')
        ->join('faculties','faculties.id','=','tutorials.facultyid')
        ->join('tutorial_types','tutorial_types.id','=','tutorials.tutorialtypeid')
        ->where('tutorials.facultyid','=',$facultyid)
        ->select('tutorials.id as tutorialid','title','subjects.name as subjectname','faculties.name as facultyname','tutorials.created_at as created_at','tutorial_types.name as tutorialtype')->get();
        
        return compact('data');
   
    }

    public function tutorialDetails($id)
    {
        $data = Tutorial::join('batches','tutorials.batchid','=','batches.id')
        ->join('courses','courses.id','=','batches.courseid')
        ->where('tutorials.id','=',$id)->first();
       
        return compact('data');
    }

    public function totalCount($batchid)
    {
        $tutorialcount = Tutorial::where('batchid','=',$batchid)->count();
        $messagecount = Message::where('batchid','=',$batchid)->count();

        return compact('tutorialcount','messagecount');
    }
}
