<?php

namespace App\Http\Controllers;

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

class MessageController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['list', 'allMessages', 'messageDetails','allFacultyMessages','store','verifyLogin']]);
    }

    // public function __construct()
    // {
    //     $this->middleware('auth', ['except' => ['list', 'checkStudentData', 'patchUpdate', 'patchUpdatePassword','messagestore', 'verifyLogin']]);
    // }

    /**
     * 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('message.index', compact('id', 'coursename', 'batch'));
    }


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

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

                $btn = '<a href="/message/' . $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;

        $messageTypes = MessageType::all(['id', 'name']);

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

    /**
     * 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);
        $message = new Message($request->input());

        $message->save();

        // $request->attachment->store('uploads');
    }

    public function verifyLogin(Request $request)
    {
        $data = Student::leftJoin('users', 'userid', '=', 'users.id')
            ->join('batches','batches.id','=','students.batchid')
            ->join('courses','courses.id','=','batches.courseid')
            ->where([['mobile', $request->mobile]])
            ->select('batches.id as batchid','courses.id as courseid','rollno','mobile', 'courses.name as coursename','students.name','students.id as studentid','users.id as userid','students.email','currentsem','batch')->first();
        if (isset($data->password)) {
            if (Hash::check($request->password, $data->password)) {
                return $data;
            }
        }
        
        return compact('data');
    }
    

    public function messagestore(Request $request)
    {


        $message = new Message($request->input());

        $message->save();

        // $request->attachment->store('uploads');
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Message  $message
     * @return \Illuminate\Http\Response
     */
    public function edit(Message $message)
    {
        $batchid = $message->batchid;
        $semester = $message->semester;
        $subjectid = $message->subjectid;
        $facultyid = $message->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;

        $messageTypes = MessageType::all(['id', 'name']);

        $messages = Message::select('id', 'messages')->first();

        return view('message.edit', compact('facultyid', 'batchid', 'subjectid', 'coursename', 'subjectname', 'batch', 'semester', 'messageTypes', 'messages'));
    }

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

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

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

    public function list()
    {
        return Message::latest()->get();
    }


    public function downloadFile($id)
    {
        $data = Message::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 allMessages($batchid)
    {
        $data = Message::join('faculties', 'faculties.id', '=', 'messages.facultyid')
            ->join('message_types', 'message_types.id', '=', 'messages.messagetypeid')
            ->where('messages.batchid', '=', $batchid)
            ->select('messages.id as messageid', 'messages', 'faculties.name as facultyname', 'messages.created_at as created_at', 'message_types.name as messagetype')->get();

        return compact('data');
    }

    public function allFacultyMessages($facultyid)
    {
        $data = Message::join('faculties', 'faculties.id', '=', 'messages.facultyid')
            ->join('message_types', 'message_types.id', '=', 'messages.messagetypeid')
            ->where('messages.facultyid', '=', $facultyid)
            ->select('messages.id as messageid', 'messages', 'faculties.name as facultyname', 'messages.created_at as created_at', 'message_types.name as messagetype')->get();

        return compact('data');
    }

    public function messageDetails($id)
    {
        $data = Message::where('id', '=', $id)->first();

        return compact('data');
    }
}
