<?php

namespace App\Controllers\Api\V1;

use Exception;
use App\Models\UsersModel;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;

class DoctorProfileController extends BaseController
{
    protected  $userModel;
    // protected  $rsaUserModel;
    // protected  $insuranceUserModel;
    public function __construct()
    {
        $this->userModel = new UsersModel();
        // $this->rsaUserModel = new RSAUsersModel();
        // $this->insuranceUserModel = new InsuranceUserModel();
    }

    public function doctorList()
    {
        try {
            $input = $this->getApiGetRequestInput($this->request);
            $page    = (int) ($input['page'] ?? 1);
            if ($page == 0) {
                $page = 1;
            }
            $perpage = (int) ($input['perPage'] ?? 10);
            if ($perpage == 0) {
                $perpage = 10;
            }
            $offset = ($page - 1) * $perpage;


            $query = $this->webdocdb->table('AspNetUsers as U')
                ->select('U.id, U.Email, U.PhoneNumber, U.UserName, U.Role, P.FirstName, P.LastName, P.Allqualifications, P.DetailedInformation, P.ApplicationUserId, P.OnlineDoctor, 
                            P.Experience, P.DoctorDutyTime, P.ImgLink, DAI.Id, DAI.OnlineStatus, DAI.ProfileMessage, DAI.Specialty,
                            AVG(F.RatingPoints) as AverageRating ,DS.Id, DS.Description as DoctorSpecialties')
                ->join('DoctorProfiles as P', 'U.id = P.ApplicationUserId', 'Left')
                ->join('DoctorAdditionalInformations as DAI', 'U.id = DAI.DoctorId', 'Left')
                ->join('FeedBacks as F', 'U.id = F.DoctorId', 'Left')
                ->join('DoctorSpecialties as DS', 'P.DoctorSpecialtyId = DS.Id', 'Left')
                ->where('U.Role', 'Employee Doctor')
                ->where('P.DoctorType', 'National')
                ->where('P.Status', 'Approved')
                ->where('P.ForPortalStatus', 'TempApproved')
                ->orWhere('P.ForPortalStatus', 'Approved')
                //     ;
                // if (!empty($input['keyword'])) {
                //     $query->groupStart()
                //         ->like('P.FirstName', $input['keyword'], 'both', null, true)
                //         ->orLike('P.LastName', $input['keyword'], 'both', null, true)
                //         ->groupEnd();
                // }
                ->groupBy('U.id, U.Email, U.PhoneNumber, U.UserName, U.Role, P.FirstName, P.LastName, P.Allqualifications, P.DetailedInformation, P.ApplicationUserId, P.OnlineDoctor, 
                           P.Experience, P.DoctorDutyTime, P.ImgLink, DAI.Id, DAI.OnlineStatus, DAI.ProfileMessage, DAI.Specialty, DS.Id, DS.Description')
                ->get($perpage, $offset);

            $result = $query->getResultArray();
            if (!empty($result)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 1,
                            'message' => "Doctors has been fetched successfully.",
                            'data' => $result,
                        ]
                    );
            } else {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => 'Sorry, there is no data found.',
                        ]
                    );
            }
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
                ResponseInterface::HTTP_OK
            );
        }
    }

    public function viewDoctorProfile()
    {
        try {
            $rules = [
                'user_id' => 'required|userExists[user_id]',
            ];
            $errors = [
                'user_id' => [
                    'required' => 'User id can not be empty.',
                    'userExists' => 'User id not exist in system.',
                ],
            ];
            $input = $this->getApiGetRequestInput($this->request);
            if (!$this->validateApiRequest($input, $rules, $errors)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => array_values($this->validator->getErrors()),
                        ],
                    );
            }

            $query = $this->webdocdb->table('AspNetUsers as U')
                ->select('U.id, U.Email, U.PhoneNumber, U.UserName, U.Role, P.FirstName, P.LastName, P.Allqualifications, Q.Title as DetailQualification, P.DetailedInformation, P.ApplicationUserId, P.OnlineDoctor, 
                        P.Experience, P.DoctorDutyTime, P.ImgLink, DAI.Id, DAI.OnlineStatus, DAI.ProfileMessage, DAI.Specialty,
                        AVG(F.RatingPoints) as AverageRating,  Count(F.RatingPoints) as RatingCount')
                ->join('DoctorProfiles as P', 'U.id = P.ApplicationUserId', 'Left')
                ->join('DoctorAdditionalInformations as DAI', 'U.id = DAI.DoctorId', 'Left')
                ->join('FeedBacks as F', 'U.id = F.DoctorId', 'Left')
                ->join('DoctorQualificationNews as Q', 'U.id = Q.DoctorProfileId', 'Left')
                ->where('U.Id', $input['user_id'])
                ->where('U.Role', 'Employee Doctor')
                ->where('P.Status', 'Approved')
                ->groupBy('U.id, U.Email, U.PhoneNumber, U.UserName, U.Role, P.FirstName, P.LastName, P.Allqualifications, P.DetailedInformation, P.ApplicationUserId, P.OnlineDoctor, 
                        P.Experience, P.DoctorDutyTime, P.ImgLink, DAI.Id, DAI.OnlineStatus, DAI.ProfileMessage, DAI.Specialty, Q.Title')
                ->get();
            $result = $query->getRowArray();
            return $this
                ->getApiResponse(
                    [
                        'statusCode' => 1,
                        'message' => "Doctor profile information has been fetched successfully.",
                        'data' => $result,
                    ]
                );
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }
}
