<?php

namespace App\Repositories;
use Illuminate\Support\Str;

use App\Models\CommunitySurveyAnswers;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;

class CommunitySurveyAnswersRepository
{
    public function __construct(
        CommunitySurveyAnswers $communitySurveyAnswers,
        CommunitySpaceUsedRepository $communitySpaceUsedRepository,
        Filesystem $filesystem,
        Mailer $mailer
    ) {
        $this->model = $communitySurveyAnswers;
        $this->communitySpaceUsedRepository = $communitySpaceUsedRepository;
        $this->file = $filesystem;
        $this->mailer = $mailer;
    }

    public function addAnswer($val, $surveyId, $community_id, $community, $survey)
    {
        $userid = 0;
        if (\Auth::check()) {
            $userid = \Auth::user()->id;
        }

        $newVal = [];

        $submit_id = date('YmdHis').rand(111, 999);

        if ($val) {
            foreach ($val as $id => $value) {
                $newValue = $value;
                if (is_array($value)) {
                    $newValue = implode(',', $value);
                }

                $answer = $this->model->newInstance();
                $answer->question_id = $id;
                $answer->answer = $newValue;
                $answer->user_id = $userid;
                $answer->survey_id = $surveyId;
                $answer->community_id = $community_id;
                $answer->submit_id = $submit_id;
                $answer->save();

                if ($newValue != '') {
                    $question = app('App\\Repositories\\CommunitySurveyQuestionsRepository')->getById($id, $community_id);
                    if ($question and $question->question_type == 'email') {
                        $mail_from_email = $community->present()->getFromEmailAddress();
                        $subject = $survey->title.' survey submitted';

                        if ($survey->submit_success_email) {
                            $email_body = $survey->submit_success_email;
                        } else {
                            $email_body = 'You have submitted successfully. Thank you for your participation.';
                        }

                        try {
                            $this->mailer->send('emails.community.survey-submitted', [
                                'site_name' => config('site_title'),
                                'email_body' => $email_body,
                                'communityId' => $community->id,
                            ], function ($mail) use ($newValue, $community, $mail_from_email, $subject) {
                                $mail->to($newValue, $newValue)
                                    ->subject($subject)
                                    ->from($mail_from_email, $community->title);
                            });
                        } catch (\Exception $e) {
                            // return $e;
                        }
                    }
                }
            }
        }

        if (isset($_FILES['documents'])) {
            foreach ($_FILES['documents']['tmp_name'] as $key => $tmp_name) {
                $images = request()->file('documents')[$key];
                if ($images != '') {
                    $logoimage = $images;

                    $filePath = 'uploads/community/'.$community_id.'/surveys/';
                    $CDNRepository = app('App\\Repositories\\CDNRepository');
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt = $logoimage->getClientOriginalExtension();

                    $file_original_ext = $fileExt;
                    $file_original_name = $logoimage->getClientOriginalName();
                    $file_original_size = $logoimage->getSize();

                    if (checkAvailableSpace($community_id, $file_original_size) != 0) {
                        $fileName = md5($logoimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
                        $logoimage_path = $filePath.$fileName;
                        $logoimage->move(public_path().'/'.$filePath, $fileName);
                        $uploadPath = 'uploads/community/'.$community_id.'/surveys/'.$fileName;
                        $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);
                        $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
                        $image = $newFileName;
                        if ($image) {
                            $answer = $this->model->newInstance();
                            $answer->question_id = $key;
                            $answer->answer = $image;
                            $answer->user_id = $userid;
                            $answer->survey_id = $surveyId;
                            $answer->community_id = $community_id;
                            $answer->submit_id = $submit_id;
                            $answer->save();

                            $fileArray = [
                                'community_id' => $community_id,
                                'user_id' => $userid,
                                'file_path' => $image,
                                'file_name' => $file_original_name,
                                'file_type' => $file_original_ext,
                                'file_size' => $file_original_size,
                                'uploaded_date' => date('Y-m-d'),
                                'type' => 'survey-answer-upload',
                                'type_id' => $surveyId,
                                'sub_type_id' => $submit_id,
                                'upload_key' => Str::random(20),
                            ];
                            $this->communitySpaceUsedRepository->save($fileArray);
                        }
                    }
                }
            }
        }

        return $submit_id;
    }

    public function addAnswerWhitepaper($val, $surveyId, $community_id, $userid = 0)
    {
        // $userid=0;
        if (\Auth::check()) {
            $userid = \Auth::user()->id;
        }

        $newVal = [];

        $submit_id = date('YmdHis').rand(111, 999);

        foreach ($val as $id => $value) {

            $newValue = $value;
            if (is_array($value)) {
                $newValue = implode(',', $value);
            }

            $answer = $this->model->newInstance();
            $answer->question_id = $id;
            $answer->answer = $newValue;
            $answer->user_id = $userid;
            $answer->survey_id = $surveyId;
            $answer->community_id = $community_id;
            $answer->submit_id = $submit_id;

            $answer->save();
        }

        if (isset($_FILES['documents'])) {
            foreach ($_FILES['documents']['tmp_name'] as $key => $tmp_name) {
                $images = request()->file('documents')[$key];
                if ($images != '') {
                    $logoimage = $images;

                    $filePath = 'uploads/community/'.$community_id.'/surveys/';
                    $CDNRepository = app('App\\Repositories\\CDNRepository');
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt = $logoimage->getClientOriginalExtension();

                    $file_original_ext = $fileExt1;
                    $file_original_name = $logoimage->getClientOriginalName();
                    $file_original_size = $logoimage->getSize();

                    if (checkAvailableSpace($community_id, $file_original_size) != 0) {
                        $fileName = md5($logoimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
                        $logoimage_path = $filePath.$fileName;
                        $logoimage->move(public_path().'/'.$filePath, $fileName);
                        $uploadPath = 'uploads/community/'.$community_id.'/surveys/'.$fileName;
                        $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);
                        $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
                        $image = $newFileName;

                        if ($image) {
                            $answer = $this->model->newInstance();
                            $answer->question_id = $key;
                            $answer->answer = $image;
                            $answer->user_id = $userid;
                            $answer->survey_id = $surveyId;
                            $answer->community_id = $community_id;
                            $answer->submit_id = $submit_id;
                            $answer->save();

                            $fileArray = [
                                'community_id' => $community_id,
                                'user_id' => \Auth::user()->id,
                                'file_path' => $image,
                                'file_name' => $file_original_name,
                                'file_type' => $file_original_ext,
                                'file_size' => $file_original_size,
                                'uploaded_date' => date('Y-m-d'),
                                'type' => 'survey-answer-upload',
                                'type_id' => $surveyId,
                                'sub_type_id' => $submit_id,
                                'upload_key' => Str::random(20),
                            ];
                            $this->communitySpaceUsedRepository->save($fileArray);
                        }
                    }
                }
            }
        }

        return $submit_id;
    }

    public function getAnswers($surveyId, $community_id)
    {
        return $this->model->where('survey_id', $surveyId)->where('community_id', $community_id)->groupBy('submit_id')->get();
    }

    public function getAnswersList($surveyId, $community_id)
    {
        return $this->model->where('survey_id', $surveyId)->where('community_id', $community_id)->groupBy('submit_id')->paginate(10);
    }

    public function getAnswersBySubmitIdsAndQuestionIds($surveyId, $community_id, array $submitIds, array $questionIds)
    {
        $submitIds = array_values(array_unique(array_filter($submitIds)));
        $questionIds = array_values(array_unique(array_filter($questionIds)));
        if (empty($submitIds) || empty($questionIds)) {
            return collect();
        }

        return $this->model
            ->where('survey_id', $surveyId)
            ->where('community_id', $community_id)
            ->whereIn('submit_id', $submitIds)
            ->whereIn('question_id', $questionIds)
            ->get(['question_id', 'submit_id', 'answer']);
    }

    public function getChoiceCountsByQuestionIds($surveyId, $community_id, array $questionIds)
    {
        $questionIds = array_values(array_unique(array_filter($questionIds)));
        if (empty($questionIds)) {
            return [];
        }

        $rows = $this->model
            ->where('survey_id', $surveyId)
            ->where('community_id', $community_id)
            ->whereIn('question_id', $questionIds)
            ->get(['question_id', 'answer']);

        $counts = [];
        foreach ($rows as $row) {
            $questionId = $row->question_id;
            if (! isset($counts[$questionId])) {
                $counts[$questionId] = [];
            }

            $raw = (string) $row->answer;
            if ($raw === '') {
                continue;
            }

            $optionIds = explode(',', $raw);
            foreach ($optionIds as $optionId) {
                $optionId = trim($optionId);
                if ($optionId === '') {
                    continue;
                }

                if (! isset($counts[$questionId][$optionId])) {
                    $counts[$questionId][$optionId] = 1;
                } else {
                    $counts[$questionId][$optionId] = $counts[$questionId][$optionId] + 1;
                }
            }
        }

        return $counts;
    }

    public function getBySurveySubmit($surveyId, $community_id, $question_id, $submit_id)
    {
        return $this->model->where('survey_id', $surveyId)->where('community_id', $community_id)->where('question_id', $question_id)->where('submit_id', $submit_id)->first();
    }

    public function getAnswer($question_id, $community_id, $option_id)
    {
        $answers = $this->model->where('question_id', $question_id)->where('community_id', $community_id)->get();

        $answerCount = 0;
        if ($answers) {
            foreach ($answers as $answer) {
                $result = explode(',', $answer->answer);

                if (in_array($option_id, $result)) {
                    $answerCount = $answerCount + 1;
                }
                /*foreach($result as $res){
                    if($res==$option_id){
                        $answerCount=$answerCount+1;
                    }
                }*/
            }
        }

        return $answerCount;
    }

    public function averageRatings($question_id, $community_id)
    {
        $total = $this->model->where('question_id', $question_id)->where('community_id', $community_id)->count();

        $sum = $this->model->where('question_id', $question_id)->where('community_id', $community_id)->sum('answer');

        $average = 0;
        if ($total and $sum) {
            $average = $sum / $total;
            $average = number_format($average, 1);
        }

        return $average;
    }

    public function getAnswerByQuest($community, $question, $data, $survey_id)
    {
        $community_id = $community->id;
        $question_id = $question->id;
        $submit_id = $data->submit_id;

        $survey = app('App\\Repositories\\CommunitySurveysRepository')->getByIdComId($survey_id, $community_id);

        $answer = $this->getBySurveySubmit($survey_id, $community_id, $question_id, $submit_id);

        $this->communitySurveyQuestionOptionsRepository = app('App\\Repositories\\CommunitySurveyQuestionOptionsRepository');

        $this->communitySurveyQuestionsRepository = app('App\\Repositories\\CommunitySurveyQuestionsRepository');

        $ans = '';
        if ($answer) {
            if ($question->question_type == 'choice') {

                $multipleOptions = explode(',', $answer->answer);

                $ansrs = '';
                foreach ($multipleOptions as $opt) {
                    $option = $this->communitySurveyQuestionOptionsRepository->getById($opt, $community->id);
                    if ($option) {
                        if ($ansrs != '') {
                            $ansrs = $ansrs.','.$option->option_title;
                        } else {
                            $ansrs = $option->option_title;
                        }
                    }
                }

                if ($question->multiple_option == 0) {
                    $mainQst = $this->communitySurveyQuestionsRepository->getByOptionId($answer->answer, $community->id);
                    if ($mainQst) {

                        $subAnswer = $this->getBySurveySubmit($survey->id, $community->id, $mainQst->id, $data->submit_id);

                        if ($subAnswer) {
                            $ansrs = $ansrs.' : '.$mainQst->question.' - '.$subAnswer->answer;
                        }

                    }
                }

                if ($ansrs) {
                    $ans = $ansrs;
                } else {
                    $ans = '';
                }
            } elseif ($question->question_type == 'rating') {
                $ans = $answer->answer.' star';
            } elseif ($question->question_type == 'file') {
                $fileUrl = $community->present()->getDocumentUrl($answer->answer);
                $ans = $fileUrl;
            } else {
                if ($answer->answer != '') {
                    $ans = $answer->answer;
                } else {
                    $ans = '';
                }
            }
        } else {
            $ans = '';
        }

        return $ans;
    }

    public function checkSurveyDuplicateEmail($val, $qid, $sid)
    {
        return $answer = $this->model
            ->where('answer', $val)
            ->where('question_id', $qid)
            ->where('survey_id', $sid)
            ->first();
    }
}

