<?php

namespace App\Http\Controllers\Api\RandDVoting;

use App\Http\Controllers\Controller;
use App\Models\RandDVoting;
use App\Models\RandDVotingPaperAnswer;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Hekmatinasser\Verta\Verta;
use App\Models\NewRandD;

class VoterController extends Controller
{
    public function storeVoting(Request $request, $id)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1066);
        }
        if (RandDVoting::where('id', $id)->where('status', '4')->first()) {
            return response()->json([
                'endVoting' => true,
                'message' => 'زمان امتیازدهی این پروژه به پایان رسیده است.',
            ]);
        } elseif (RandDVoting::where('id', $id)->where('status', '2')->first()) {
            $all = $request->all();
            $questions = json_decode($request->questions);
            foreach ($questions as $value) {
                $new = new RandDVotingPaperAnswer();
                $new->vote_id = $id;
                $new->score = $value->score;
                $new->score_type = $value->type;
                $new->description = $all['desc'];
                $new->q_id = $value->q_id;
                $new->q_fa = $value->q_fa;
                $new->user_id = Auth::user()->id;
                $new->fullname = $all['fullname'];
                $new->save();
            }
            return response()->json([
                'endVoting' => false,
                'message' => 'success'
            ]);
        }
    }

    public function showResult($id)
    {
        $project = NewRandD::find($id);
        if($project->project_status == 3)
        {
            return response()->json([
                'message' => 'success',
                'data' => [
                    'id' => $project->id,
                    'project_status' => $project->project_status,
                    'project_name' => $project->title,
                    'reject_description' => $project->reject_description,
                ]
            ]);  
        }

        $vote = RandDVoting::where('project_id', $id)->first();
        // if vote has not finished, result is 403 forbidden
        if ($vote->status != '4') {
            abort(403);
        }

        

        /// get users data
        $participants = DB::table('randd_voting_paper_answers')
                        ->where('vote_id', $vote->id)
                        ->join('users', 'randd_voting_paper_answers.user_id', 'users.id')
                        ->groupBy('user_id')
                        ->get();

        $getScores = RandDVotingPaperAnswer::where('score_type', 1)
                            ->where('vote_id', $vote->id)
                            ->get();
        $countScoresNumber = count($getScores);
        
        $average = round(RandDVotingPaperAnswer::where('vote_id', $vote->id)
                                        ->where('score_type', 1)
                                        ->sum('score') / count($participants),1);
        
        $typePercentsNumber = RandDVotingPaperAnswer::where('vote_id', $vote->id)
                                            ->where('score_type', 2)
                                            ->count();
                                            
        $typeOneScore = RandDVotingPaperAnswer::where('vote_id', $vote->id)
                                            ->where('score_type', 2)
                                            ->where('score', '1')
                                            ->count();

        $typeTwoScore = RandDVotingPaperAnswer::where('vote_id', $vote->id)
                                            ->where('score_type', 2)
                                            ->where('score', '2')
                                            ->count();

        $typeThreeScore = RandDVotingPaperAnswer::where('vote_id', $vote->id)
                                            ->where('score_type', 2)
                                            ->where('score', '3')
                                            ->count();
                                            
        
        
        // General voting information
        $data = [
            'id' => $vote->id,
            'project_type' => $vote->project->status,
            'project_name' => $vote->project->title,
            'project_status' => $vote->project->project_status,
            'description' => $vote->description,
            'status' => $vote->status,
            'participants_number' => count($participants),
            'participants' => $participants,
            'voterـstarter' => $vote->user->first_name . ' ' . $vote->user->last_name,
            'average' => $average,
            'typeOne' => $typeOneScore / $typePercentsNumber * 100,
            'typeTwo' => $typeTwoScore / $typePercentsNumber * 100,
            'typeThree' => $typeThreeScore / $typePercentsNumber * 100,
        ];

        $data['votingUsersResult'] = false;
        if (Auth::user()->can('member-RandD')) {
            $data['votingUsersResult'] = true;
        } else {
            if (Auth::user()->can('staff-RandD')) {
                $data['votingUsersResult'] = true;
            } else {
                // permission for ostani users
                if (Auth::user()->province_id) {
                    $data['votingUsersResult'] = false;
                } else {
                    // permission for setadi users
                    $data['votingUsersResult'] = false;
                }
            }
        }

        return response()->json([
            'message' => 'success',
            'data' => $data
        ]);
    }

    public function showUserPaper(Request $request)
    {
        $r = RandDVotingPaperAnswer::where('vote_id', $request->vote)
                                    ->where('user_id', $request->user)
                                    ->get();
        $ar = [];
        foreach ($r as $item) {
            $ar['questions'][] = [
                'question_id' => $item->q_id,
                'question_fa' => $item->q_fa,
                'score' => $item->score,
                'score_type' => $item->score_type,
            ];
            $ar['sum_score'] = RandDVotingPaperAnswer::where('vote_id', $request->vote)
                                                    ->where('user_id', $request->user)
                                                    ->where('score_type', 1)
                                                    ->sum('score');
            $ar['fullname'] = $item->fullname;
            $ar['description'] = $item->description;
            $ar['created_at'] = Verta::instance($item->created_at);
        }
        return $ar;
    }
}