<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\API\v1\NotificationController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class CommentController extends BaseController
{

    // Show all comments of media (main and reply distincts)

    public function showAll(Request $request,$media_id)
    {
        try {

            $users_ids = [];
            $comments_p = [];
            $comments_s = [];

            // Get ID of all users who have commented (commentaires principaux)
            $users_ids_1 = DB::connection('tenant')
            ->table('commentaires')
            ->where('media_id','=',$media_id)
            ->where('comment_id','=',null)
            ->get()
            ->pluck('user_id')
            ->toArray();

            // --Check if media has a comment
            if(count($users_ids_1) == 0){
                return sendResponse([
                    'profs' => [],
                    'students' => [],
                    'comments' => [
                        'comment_p' => [],
                        'comment_s' => [],
                    ]
                ],'NO_COMMENT_FOR_THIS_MEDIA');
            }

            $users_ids = array_unique($users_ids_1);

            $comments_p = DB::connection('tenant')
            ->table('commentaires')
            ->where('media_id','=',$media_id)
            ->where('comment_id','=',null)
            ->join('users','commentaires.user_id','=','users.id')
            ->orderBy('commentaires.created_at')
            ->select(
                'users.matricule',
                'commentaires.id','commentaires.comment_text','commentaires.rate','commentaires.created_at'
            )
            ->get();

            // Get ID of all users who have commented (commentaires secondaires)
            $users_ids_2 = DB::connection('tenant')
            ->table('commentaires')
            ->where('media_id','=',$media_id)
            ->where('comment_id','!=',null)
            ->get()
            ->pluck('user_id')
            ->toArray();

            if(count($users_ids_2) != 0) {
                $users_ids_2 = array_unique($users_ids_2);
                $users_ids = array_merge($users_ids, $users_ids_2);

                $comments_s = DB::connection('tenant')
                    ->table('commentaires')
                    ->where('media_id','=',$media_id)
                    ->where('comment_id','!=',null)
                    ->join('users','commentaires.user_id','=','users.id')
                    ->orderBy('commentaires.created_at')
                    ->select(
                        'users.matricule',
                        'commentaires.id','commentaires.comment_text','commentaires.rate','commentaires.comment_id','commentaires.created_at'
                    )
                    ->get()
                    ->groupBy('comment_id');

                $comments_s = encryptKeys($comments_s);
            }


            // Get users' data from GestStudent 
            // --Profs
            $server_response = $this->getProfData($users_ids);
            if($server_response && $server_response['success']){

                $profs_data = $server_response['data'];

            } else {
                return sendError("ERROR_GETTING_PROF_INFOS", [], 500);
            }

            // --Students
            $server_response = $this->getStudentData($users_ids);
            if($server_response && $server_response['success']){

                $students_data = $server_response['data'];

            } else {
                return sendError("ERROR_GETTING_STUDENTS_INFOS", [], 500);
            }

            return sendResponse([
                'profs' => $profs_data,
                'students' => $students_data,
                'comments' => [
                    'comment_p' => $comments_p,
                    'comment_s' => $comments_s
                ]
            ],'DATA_GOT_SUCCESSFULLY');

        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 500);
        }
    }

    // Store a comment

    public function store(Request $request)
    {
        try {

            $notif = new NotificationController();

            $result = [];

            $userId = $request->get('User')->id;

            $commentId = DB::connection('tenant')
                ->table('commentaires')
                ->insertGetId([
                    'comment_text' => isset($request->comment_text) ? $request->comment_text : null,
                    'rate' => $request->rate,
                    'user_id' => $userId,
                    'media_id' => $request->media_id,
                    'comment_id' => isset($request->comment_id) ? $request->comment_id : null
                ]);

            $ecu_id = DB::connection('tenant')
                ->table('medias')
                ->where('id',$request->media_id)
                ->get()->first()->ecu_id;

            $request['ecu_id'] = $ecu_id;
            $request['user_id'] = $userId;

            // TODO : Make notif process async toward comments !
            if ($request->rate != 0) {
                $request['type'] = 'RATE';
                $result['rate_notif'] = $notif->store_notification($request);
            } else {
                if (isset($request->comment_text)) {
                    $request['type'] = 'COMMENTAIRE';
                    $result['comment_notif'] = $notif->store_notification($request);
                }
            }

            $comment = DB::connection('tenant')
                ->table('commentaires')
                ->where('id', $commentId)
                // ->get()
                ->first();

            return sendResponse($comment,'DATA_GOT_SUCCESSFULLY');

        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
        }

    }

    // Get from GestStudent API profs data

    private function getProfData($users_ids){

        // Get their matricules
        $profs_matricules = DB::connection('tenant')
        ->table('users')
        ->whereIn('id',$users_ids)
        ->where('type_user','=',4)
        ->get()
        ->pluck('matricule')
        ->toArray();

        if (count($profs_matricules) == 0) {
            // prevent calling GestStudent as no prof has commented !
            return  [
                'success' => true,
                'data' => [],
            ];
        }

        return reqGest('POST','v1/users/data',['matricules_array' => $profs_matricules],2);
    }

    // Get from GestStudent API students data

    private function getStudentData($users_ids){

        // Get their matricules
        $students_matricules = DB::connection('tenant')
        ->table('users')
        ->whereIn('id',$users_ids)
        ->where('type_user','=',0)
        ->get()
        ->pluck('matricule')
        ->toArray();

        if (count($students_matricules) == 0) {
            // prevent calling GestStudent as no students have commented media !
            return  [
                'success' => true,
                'data' => [],
            ];
        }

        return reqGest('POST','v1/users_student/data', ['matricules_array' => $students_matricules],2);

    }

}
